public class ArraySearcher
1: //ArraySearcher.java
3: import java.util.Scanner;
5: /**
6: Class for searching an already sorted array of integers.
7: */
8: public class ArraySearcher
9: {
10: private Scanner keyboard = new Scanner(System.in);
11: private int[] a;
13: /**
14: Precondition: theArray is full and is sorted
15: from lowest to highest.
16: */
17: public ArraySearcher
18: (
19: int[] theArray
20: )
21: {
22: a = theArray; //a is now another name for theArray.
23: }
25: /**
26: If target is in the array, returns the index of an occurrence
27: of target. Returns -1 if target is not in the array.
28: */
29: public int find
30: (
31: int target //in
32: )
33: {
34: return binarySearch(target, 0, a.length - 1);
35: }
37: //Uses binary search to search for target in a[first] through
38: //a[last] inclusive. Returns the index of target if target
39: //is found. Returns -1 if target is not found.
40: private int binarySearch
41: (
42: int target,
43: int first,
44: int last
45: )
46: {
47: int result;
48: if (first > last)
49: result = -1;
50: else
51: {
52: int mid = (first + last) / 2;
53: System.out.println("Now looking at value " + a[mid]); //added
54: System.out.print("Press Enter to continue ... "); //added
55: keyboard.nextLine(); //added
56: if (target == a[mid])
57: result = mid;
58: else if (target < a[mid])
59: result = binarySearch(target, first, mid - 1);
60: else //(target > a[mid])
61: result = binarySearch(target, mid + 1, last);
62: }
63: return result;
64: }
65: }