// Connor Moore, CSE 143 // Runs the binary search algorithm on a list of TAs. import java.util.*; public class Search { public static void main(String[] args) { List tas = new ArrayList(); tas.add("Alan"); tas.add("Halden"); tas.add("Shobhit"); tas.add("Tanvi"); tas.add("Cody"); tas.add("Melissa"); tas.add("Chloe"); System.out.println(tas); Collections.sort(tas); System.out.println(tas); int cody = binarySearch(tas, "Cody"); System.out.println(cody); int connor = binarySearch(tas, "Connor"); System.out.println(connor); } // Returns the index of target in list using the binary search algorithm. If // target is not in list, returns -(insertion point + 1). // Pre: list is sorted in ascending order; result is undefined otherwise public static int binarySearch(List list, String target) { // notice the exclusive upper bound return binarySearch(list, target, 0, list.size()); } // 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(List list, String target, int min, int max) { if (min >= max) { return -(min + 1); } else { // split the list in 2 int mid = (max + min) / 2; if (target.compareTo(list.get(mid)) == 0) { return mid; } else if (target.compareTo(list.get(mid)) < 0) { // search left half if ... target < "midpoint" return binarySearch(list, target, min, mid); } else { // otherwise search right half return binarySearch(list, target, mid + 1, max); } } } }