/* This is a program that tests the running time of binary search. It initializes an array of random numbers, and then calls binary search NB_TESTS times on it, each time with a randomly generated target. Laura Toma csci 101 */ //to use random numbers import java.util.Random; public class BinSearchTest { public static void main (String args[]) { final int SIZE = 1000000; final int NB_TESTS = 100000; // a random number generator Random rand = new Random(); //declare variable r that knows to read from user ReadStream r = new ReadStream(); //declare and allocate array int[] a = new int [SIZE]; //initialize array in increasing order int i=0; while (i < SIZE) { a[i] =i; i++; } System.out.println("test array size: " + SIZE); int target, left, right, middle; boolean found; /* run NB_TESTS searches with a random target */ // start for timing information long startTime = System.currentTimeMillis(); i = 0; while (i< NB_TESTS) { //returns a random number in the range 0 to SIZE-1 target = rand.nextInt(SIZE); //System.out.println("checking target = " + target); //binary search for target in a[] left = 0; right = SIZE-1; found = false; while (right >= left && found == false) { middle = (left + right)/2; if (a[middle] == target) found = true; if (a[middle] < target) left = middle +1; if (a[middle] > target) right = middle -1; } i++; } // end of timing long endTime = System.currentTimeMillis(); // some timing statistics double totalTimeSeconds = (endTime - startTime)/1000.0; System.out.println(NB_TESTS + " binary searches done."); System.out.println("total time = " + totalTimeSeconds + " seconds"); System.out.println("avg time per search = " + totalTimeSeconds/NB_TESTS + " seconds"); } // end of main } // end of class