/* Search.java CIS 160 11/08/04 Demonstration of linear and binary searching. */ import java.text.*; public class Search { public static void main(String[] args) { long startTime, elapsedTime; int hits, misses; char[] spin = { '|', '/', '-', '\\' }; int spinNdx = 0; DecimalFormat df = new DecimalFormat("0.00"); 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; } }