import java.util.*; // for Random /** * CSE 403, Winter 2010, Marty Stepp * This program compares the runtime of the sequential and binary * search algorithms. You can change the LENGTH and SEARCHES constants to * run it with a different amount of elements a different number of times. * Basically we just used this program to play with the assert keyword (line 39). */ public class Searching { private static final Random RAND = new Random(); // global random generator private static final int LENGTH = 4000000; // length of array to search private static final int SEARCHES = 1000; // 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++) { a[0] = Integer.MAX_VALUE; 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 -1 if the value is not found in the array. * @pre The array must be sorted. If the array is not sorted, the result * is undefined. * @throws NullPointerException if a is null. */ public static int binarySearch(int[] a, int value) { assert isSorted(a); return binarySearch(a, value, 0, a.length - 1); } // recursive private helper for search; examines given range of indexes private static int binarySearch(int[] a, int value, int min, int max) { // base case: no elements if (min > max) { return -1; } else { int mid = (min + max) / 2; if (a[mid] == value) { return mid; // found it! } else if (a[mid] < value) { // search the right portion of the array return binarySearch(a, value, mid + 1, max); } else { // a[mid] > value // search the left portion of the array return binarySearch(a, value, min, mid - 1); } } } /** * Creates an array of the given length, fills it with random data, * arranges it into sorted order, and returns it. * @pre length >= 0 */ 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; } /** * Returns true if the given array is sorted, false otherwise. * @pre a is not null */ public static boolean isSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i+1]) { return false; } } return true; } }