public class binDemo
1: public class binDemo
2: {
3: public static int binarySearch(int anArray[], int first, int last, int value)
4: {
5: int index;
6:
7: if(first > last)
8: {
9: index = -1; //value not in original array
10: }
11: else
12: {
13: int mid = (first + last)/2;
14:
15: if(value == anArray[mid])
16: {
17: index = mid; //value found at anArray[mid]
18: }
19: else if(value < anArray[mid])
20: {
21: index = binarySearch(anArray, first, mid-1, value);
22: }
23: else
24: {
25: index = binarySearch(anArray, mid+1, last, value);
26: }
27: }
28:
29: return index;
30: }
31:
32: public static void main(String[] arg)
33: {
34: //Create a sorted array
35: int[] myArray = {0,1,9,13,24,35,46,57,68,79,110,
36: 111,212,213,314,315,416,417,418,419,520};
37: int start = 0; //indicates the beginning index
38: int end = myArray.length; //indicates the last index
39:
40: //locate the following values in the array
41: int x = 9;
42: int y = 416;
43: int z = 75;
44: int result; //result of search
45:
46: System.out.println("Searching for " + x);
47: try
48: {
49: result = binarySearch(myArray, start, end, x);
50: }
51: catch(ArrayIndexOutOfBoundsException e)
52: {
53: result = -1;
54: }
55:
56: if(result >= 0) //value located
57: System.out.println("Value " + x + " located at position " + result);
58: else
59: System.out.println("Value " + x + " not located!");
60:
61: System.out.println("Searching for " + y);
62: try
63: {
64: result = binarySearch(myArray, start, end, y);
65: }
66: catch(ArrayIndexOutOfBoundsException e)
67: {
68: result = -1;
69: }
70:
71: if(result >= 0) //value located
72: System.out.println("Value " + y + " located at position " + result);
73: else
74: System.out.println("Value " + y + " not located!");
75:
76: System.out.println("Searching for " + z);
77: try
78: {
79: result = binarySearch(myArray, start, end, z);
80: }
81: catch(ArrayIndexOutOfBoundsException e)
82: {
83: result = -1;
84: }
85: if(result >= 0) //value located
86: System.out.println("Value " + z + " located at position " + result);
87: else
88: System.out.println("Value " + z + " not located!");
89: }
90: }