// Helene Martin, CSE 143 // Runs the binary search algorithm on a list of TAs. import java.util.*; public class Search { public static void main(String[] args) { ArrayList tas = new ArrayList(); tas.add("Molly"); tas.add("Connor"); tas.add("Solai"); tas.add("Todd"); tas.add("Eden"); tas.add("Kevin"); tas.add("Mike"); Collections.sort(tas); System.out.println(tas); int mike = binarySearch(tas, "Mike"); System.out.println(mike); int hayley = binarySearch(tas, "Hayley"); System.out.println(hayley); } // Returns the index of target in l using the binary search algorithm. If // target is not in l, returns -(insertion point + 1). // Pre: l is sorted in ascending order; result is undefined otherwise public static int binarySearch(ArrayList l, String target) { return binarySearch(l, target, 0, l.size() - 1); } // Returns the index of target in l between min and max using the binary // search algorithm. If target is not in l, returns -(insertion point + 1). // Pre: l is sorted in ascending order; result is undefined otherwise private static int binarySearch(ArrayList l, String target, int min, int max) { // base cases: // - only name we're looking for is left // - no names are left int mid = (min + max) / 2; int compare = target.compareTo(l.get(mid)); if (compare == 0) { // found the target return mid; } else if (min > max) { // no names are left return -(min + 1); // or simply -1 but this gives more info } else if (compare > 0) { return binarySearch(l, target, mid + 1, max); // right side } else { return binarySearch(l, target, min, mid - 1); // left side } } }