Binary search of an ordered list

BINARY SEARCH
  i := 1
  j := n
  while (i<j) do
        m := [ (i+j)/2 ]
        if (x > am) then
           i := m+1
        else
           j := m
  if (x ≠ ai) then
     i := 0
  return i

Worst case analysis

C(1) = 1
C(2) = 2
C(n) = 1 + C( ceil(n/2) )
        = 2 + C( ceil(n/22) )
...
        = ceil(lg n) + C(1)
        = ceil(lg n) + 1

Average case analysis

CASE 1:  x is in the list (equal distribution)

Let n = 2k + r,     0 ≤ r < 2k     (r < n/2)

We always do k iterations;
we sometimes (2r/n of the time) do an extra one.

A = k + 2r/n,     where k = [lg n]

CASE 2:  x is not in the list (n+1 intervals equally likely)

Each interval goes with the succeeding list member.
(The last interval goes with the last list member.)

The last list member never requires an extra iteration.

A = k + 2r/(n+1),     where k = [lg n]


Dan Hirschberg
Last modified: Oct 28, 2003