/* This is a program that tests the running time of sequential 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 SeqSearchTest { 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, start; boolean found; /* run NB_TESTS searches wi th 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); //search sequentially for target in a[] start = 0; found = false; while (start < SIZE && found == false) { if (a[start] == target) found = true; else start++; } i++; } // end of timing long endTime = System.currentTimeMillis(); // some timing statistics double totalTimeSeconds = (endTime - startTime)/1000.0; System.out.println(NB_TESTS + " sequential 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