Java Reference
In-Depth Information
Display 11.8
Using the search Method
1 public class BinarySearchDemo
2 {
3 public static void main(String[] args)
4 {
5 int [] a = {-2, 0, 2, 4, 6, 8, 10, 12, 14, 16};
6 int finalIndex = 9;
7 System.out.println("Array contains:");
8 for ( int i = 0; i < a.length; i++)
9 System.out.print(a[i] + " ");
10 System.out.println();
11 System.out.println();
12 int result;
13 for ( int key = -3; key < 5; key++)
14 {
15 result = BinarySearch.search(a, 0, finalIndex, key);
16 if (result >= 0)
17 System.out.println(key + " is at index " + result);
18 else
19 System.out.println(key + " is not in the array.");
20 }
21 }
22 }
Sample Dialogue
Array contains:
-2 0 2 4 6 8 10 12 14 16
-3 is not in the array.
-2 is at index 0
-1 is not in the array.
0 is at index 1
1 is not in the array.
2 is at index 2
3 is not in the array.
4 is at index 3
 
Search WWH ::




Custom Search