Iterative Binary Search
by Isai Damier, Android Engineer @ Google

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/***********************************************************************
 * Author: Isai Damier
 * Title: Iterative Binary Search
 * Project: geekviewpoint
 * Package: algorithms
 *
 * Statement:
 *   Given a sorted array and an element, find the index of the element.
 *   Return -1 otherwise.
 *
 *  Time Complexity: O(lg n)
 *    where n is the size of the array
 *
 * Sample Input: {1,2,3,5,7,8,11,13,17,19,21}; 11
 * Sample Output: 6
 *
 * Technical Details: This is among the most intuitive algorithms in
 *   the world. And yet many experts have historically gotten it
 *   wrong (i.e. your nearest textbook may have it wrong). The idea
 *   is to continuously split the array until the element is found
 *   (or not).
 *  
 *   Because binary search is achieved by continuously doing the same
 *   process on ever smaller size of the problem, the solution can
 *   also be defined using recursion.
 *                       _
 *                      |
 *                      | bs(A[1...n/2-1],el)   if el < A[n]
 *    bs(A[1...n],el) = | bs(A[n/2+1...n],el)   if el > A[n]
 *                      | n                     if el == A[n]
 *                      |_
 *  
 *   see implementation at
 *
 **********************************************************************/
 public int binarySearchIterative(int[] A, int el) {
  int min = 0, max = A.length - 1, mid;
  while (min <= max) {
    mid = min + (max - min) / 2;
    if (el == A[mid]) {
      return mid;
    } else if (el > A[mid]) {
      min = mid + 1;
    } else {
      max = mid - 1;
    }
  }//while
  return -1;
}