// 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) { String[] tasTemp = { "Kristie", "Daniel", "Adam", "Tore", "Riley", "Dian", "Clint" }; List tas = Arrays.asList(tasTemp); Collections.sort(tas); System.out.println(tas); int kristie = binarySearch(tas, "Kristie"); System.out.println(kristie); int shiny = binarySearch(tas, "Shiny"); System.out.println(shiny); } // 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(List l, String target) { return binarySearch(l, target, 0, l.size() - 1); } // Returns the index of target in l. Uses min and max to constrain which // portion of l is considered. private static int binarySearch(List l, String target, int min, int max) { int mid = (min + max) / 2; if (l.get(mid).equals(target)) { return mid; } else if (min > max) { return -(min + 1); } else if (l.get(mid).compareTo(target) < 0) { return binarySearch(l, target, mid + 1, max); } else { return binarySearch(l, target, min, mid - 1); } } }