// CSE 143, Winter 2010, Marty Stepp // This program compares the runtime of sequential and binary search. import java.util.*; // for Random public class Searching { private static final Random RAND = new Random(); // global random generator // sequential: 40,000 x 1,000 in ~2.5 sec // binary: 10,000,000 x 4,000,000 in ~2.5 sec private static final int LENGTH = 10000000; // length of array to search private static final int SEARCHES = 4000000; // number of searches to perform public static void main(String[] args) { System.out.println("Creating the array...\n"); int[] a = createArray(LENGTH); System.out.println("Performing searches...\n"); long startTime = System.currentTimeMillis(); // perform many searches and time how long it takes for (int i = 1; i <= SEARCHES; i++) { int index = binarySearch(a, 42); if (index >= 0 && a[index] != 42) { throw new RuntimeException("search returned an incorrect answer"); } } long endTime = System.currentTimeMillis(); long elapsedTime = endTime - startTime; System.out.println(elapsedTime + " ms to perform " + SEARCHES + " searches over " + LENGTH + " elements"); } // Returns the index of the given value in the given array of integers, // or a negative number if the value is not found in the array. // Precondition: The array must be sorted. If the array is not sorted, // the result is undefined. // Throws a NullPointerException if a is null. public static int binarySearch(int[] a, int value) { return binarySearch(a, value, 0, a.length - 1); } // recursive private helper for search; examines given range of indexes public static int binarySearch(int[] a, int value, int min, int max) { if (min > max) { // not found; return negative answer return -(min + 1); } else { int mid = (max + min) / 2; if (a[mid] == value) { return mid; } else if (a[mid] < value) { // go right; look at (mid+1 -> max) return binarySearch(a, value, mid + 1, max); } else { // a[mid] > value // go left; look at (min -> mid-1) return binarySearch(a, value, min, mid - 1); } } } // Returns the index of the given value in the given array of integers, // or -1 if the value is not found in the array. // Throws a NullPointerException if a is null. public static int sequentialSearch(int[] a, int value) { for (int i = 0; i < a.length; i++) { if (a[i] == value) { return i; } } return -1; } // Creates an array of the given length, fills it with random data, // arranges it into sorted order, and returns it. public static int[] createArray(int length) { int[] a = new int[length]; for (int i = 0; i < a.length; i++) { a[i] = RAND.nextInt(1000000000); } Arrays.sort(a); return a; } }