1 /**
2 A class for executing binary searches through an array.
3 */
4 public class BinarySearcher
5 {
6 private int[] a;
7
8 /**
9 Constructs a BinarySearcher.
10 @param anArray a sorted array of integers
11 */
12 public BinarySearcher(int[] anArray)
13 {
14 a = anArray;
15 }
16
17 /**
18 Finds a value in a sorted array, using the binary
19 search algorithm.
20 @param v the value to search
21 @return the index at which the value occurs, or -1
22 if it does not occur in the array
23 */
24 public int search(int v)
25 {
26 int low = 0;
27 int high = a.length - 1;
28 while (low <= high)
29 {
30 int mid = (low + high) / 2;
31 int diff = a[mid] - v;
32
33 if (diff == 0) // a[mid] == v
34 return mid;
35 else if (diff < 0) // a[mid] < v
36 low = mid + 1;
37 else
38 high = mid - 1;
39 }
40 return -1;
41 }
42 }
43