/* Search.java CIS 160 David Klick 2015-09-19 Demonstration of linear and binary searching. */ public class Search { public static void main(String[] args) { long startTime, elapsedTime; int hits, misses; char[] spin = { '|', '/', '-', '\\' }; int spinNdx = 0; int[] arr = new int[100000]; // create an array of somewhat random integers // that is in sequential order int x = 0; for (int i=0; i key) return -1; } return -1; } // binarySearch will search through an int array // for any key. It returns -1 if the key is not found. // If the key is found, it returns the position in the // array it was found at. The array must be sorted in // ascending order. public static int binarySearch(int[] a, int key) { int hi = a.length - 1; int lo = 0; int middle; while (hi >= lo) { middle = (hi + lo) / 2; if (a[middle] == key) return middle; else if (a[middle] > key) hi = middle - 1; else lo = middle + 1; } return -1; } } /* Sample run: First linear search: Hits: 99904 Misses: 100096 Elapsed time: 4.902447 sec Second linear search: Hits: 99904 Misses: 100096 Elapsed time: 4.697402 sec Binary search: Hits: 99904 Misses: 100096 Elapsed time: 0.019242 sec */