import java.util.*; /** * Sequential and binary searches * Code from CSE142 lecture, 2/03 * Author: Hal Perkins * (Note: to use this code, you would need to add strings to the list and, * for binary search, the strings would have to be in alphabetical order.) */ public class Search { // instance variable private ArrayList names; // list of Strings /** Construct empty list */ public Search() { names = new ArrayList(); } /** Add str to the list */ public void add(String str) { names.add(str); } /** Return a string with the list elements */ public String toString() { if (names.size() == 0) { return ""; } // at least one string String result = (String)names.get(0); for (int k = 1; k < names.size(); k++) { result = result + " " + (String)names.get(k); } return result; } /** return location of str in the list, or -1 if not found */ public int linearSearch(String str) { // linear (sequential) search for (int k = 0; k < names.size(); k++) { if (str.equals((String)names.get(k))) { return k; } } // not found if control reaches here return -1; } /** return location of str in the list, or -1 if not found. * precondition: List is sorted, i.e., names(1) <= names(2) <= ... */ public int binarySearch(String str) { // binary search // invariant: names(0..L) <= str, names(R..size()-1) > str // names(L+1..R-1) is the unknown region in the middle int L = -1; int R = names.size(); while (L+1 != R) { int mid = (L + R) / 2; if (((String)names.get(mid)).compareTo(str) <= 0) { L = mid; } else { R = mid; } } // if found, str equals names(L), but need to guard against L=-1 if all // elements in names are > str if (L >= 0 && ((String)names.get(L)).equals(str)) { return L; } else { return -1; } } }