// Allison Obourn // CSE 143 - lecture 14 // 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("Jacob"); tas.add("Jessica"); tas.add("Meredith"); tas.add("John"); tas.add("Autumn"); tas.add("Tyler"); tas.add("Derek"); Collections.sort(tas); System.out.println(tas); int meredith = binarySearch(tas, "Meredith"); System.out.println(meredith); int madison = binarySearch(tas, "Madison"); System.out.println(madison); } // 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 list between min and max using the binary // search algorithm. If target is not in list, 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) { 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); } else if (compare > 0) { return binarySearch(list, target, mid + 1, max); // right side } else { return binarySearch(list, target, min, mid - 1); // left side } } }