Thursday, April 26, 2012

On Binary Search

Recently failed a quixey challenge on binary search and went over the Knuth v3, although the notes below are from some code I have seen before.

Everybody knows binary search, but not good enough to write a perfect one.

Here the problem asks for something similar to c++ stl lower_bound

Given a[0..n-1] with a[0]<= a[1] <=... <= a[n-1], and int x, return pos such that if we insert x at pos, the order of a[] is preserved, that is, pos is such that
a[0]<= a[1] <=... <= a[pos-1] <= x < a[pos] <= ... <= a[n-1]
The version presented below has the invariants:
  1. 1. m is a valid index, that is, 0 <= m < n
  2. 2. each iteration, either l or u gets updated.
  3. 3. a[l] < x and a[u] <= x. This is done by using phantom element a[-1] and a[n]
  4. 4. Inside loop, l < m < n
  5. 5. Outside loop, l+1=u
binsearch(a[0..n-1], int x) // returns first pos such that a[pos]>=x
l=-1, u=n 
while l+1 < u
  m = (l+u)/2
  if (a[m]

No comments:

Post a Comment