public class BinarySearchDemo
1: //BinarySearchDemo.java
3: import java.util.Scanner;
5: public class BinarySearchDemo
6: {
7: private static int binarySearch(int[] numbers, int key)
8: {
9: // Variables to hold the low, middle and high indices
10: // of the area being searched. Starts with entire range.
11: int low = 0;
12: int mid = numbers.length / 2;
13: int high = numbers.length - 1;
15: // Loop until "low" passes "high"
16: while (high >= low)
17: {
18: // Calculate the middle index
19: mid = (high + low) / 2;
21: // Cut the range to either the left or right half,
22: // unless numbers[mid] is the key
23: if (numbers[mid] < key)
24: {
25: low = mid + 1;
26: }
27: else if (numbers[mid] > key)
28: {
29: high = mid - 1;
30: }
31: else
32: {
33: return mid;
34: }
35: }
37: return -1; // not found
38: }
40: // Main program to test the binarySearch() method
41: public static void main(String[] args)
42: {
43: int[] numbers = { 2, 4, 7, 10, 11, 32, 45, 87 };
44: System.out.print("NUMBERS: ");
45: for (int i = 0; i < numbers.length; i++)
46: {
47: System.out.print(numbers[i] + " ");
48: }
49: System.out.println();
51: Scanner scnr = new Scanner(System.in);
52: System.out.print("Enter an integer value: ");
53: int key = scnr.nextInt();
54: int keyIndex = binarySearch(numbers, key);
56: if (keyIndex == -1)
57: {
58: System.out.println(key + " was not found.");
59: }
60: else
61: {
62: System.out.printf("Found %d at index %d.\n", key, keyIndex);
63: }
64: }
65: }