// Zorah Fung, 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("Natalie"); tas.add("Aishwarya"); tas.add("Shobhit"); tas.add("Tyler"); tas.add("Emily"); tas.add("Karan"); tas.add("Meredith"); System.out.println(tas); Collections.sort(tas); System.out.println(tas); int meredith = binarySearch(tas, "Meredith"); System.out.println(meredith); int shannon = binarySearch(tas, "Shannon"); System.out.println(shannon); } // 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) { return binarySearch(list, target, 0, list.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(List list, 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(list.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(list, target, mid + 1, max); // right side } else { return binarySearch(list, target, min, mid - 1); // left side } } }