1// Java implementation of iterative Binary Search
2class BinarySearch {
3 // Returns index of x if it is present in arr[],
4 // else return -1
5 int binarySearch(int arr[], int x)
6 {
7 int l = 0, r = arr.length - 1;
8 while (l <= r) {
9 int m = l + (r - l) / 2;
10
11 // Check if x is present at mid
12 if (arr[m] == x)
13 return m;
14
15 // If x greater, ignore left half
16 if (arr[m] < x)
17 l = m + 1;
18
19 // If x is smaller, ignore right half
20 else
21 r = m - 1;
22 }
23
24 // if we reach here, then element was
25 // not present
26 return -1;
27 }
28
29 // Driver method to test above
30 public static void main(String args[])
31 {
32 BinarySearch ob = new BinarySearch();
33 int arr[] = { 2, 3, 4, 10, 40 };
34 int n = arr.length;
35 int x = 10;
36 int result = ob.binarySearch(arr, x);
37 if (result == -1)
38 System.out.println("Element not present");
39 else
40 System.out.println("Element found at "
41 + "index " + result);
42 }
43}
1public int runBinarySearchRecursively(
2 int[] sortedArray, int key, int low, int high) {
3 int middle = (low + high) / 2;
4
5 if (high < low) {
6 return -1;
7 }
8
9 if (key == sortedArray[middle]) {
10 return middle;
11 } else if (key < sortedArray[middle]) {
12 return runBinarySearchRecursively(
13 sortedArray, key, low, middle - 1);
14 } else {
15 return runBinarySearchRecursively(
16 sortedArray, key, middle + 1, high);
17 }
18}
19
1// Returns index of key in sorted list sorted in
2// ascending order
3public static int binarySearch(List slist, T key)
4
5// Returns index of key in sorted list sorted in
6// order defined by Comparator c.
7public static int binarySearch(List slist, T key, Comparator c)
8
9If key is not present, the it returns "(-(insertion point) - 1)".
10The insertion point is defined as the point at which the key
11would be inserted into the list.