Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have only one comparison per iteration of a binary search algorithm?

In binary search algorithm we have two comparisons:

if (key == a[mid]) then found;

else if (key < a[mid]) then binary_search(a[],left,mid-1);
      else binary_search(a[],mid+1,right);

Is there a way by which I can have only one comparison instead of the above two.

--

Thanks

Alok.Kr.

like image 736
Kumar Alok Avatar asked Aug 17 '10 07:08

Kumar Alok


1 Answers

See:

http://en.wikipedia.org/wiki/Binary_search_algorithm#Single_comparison_per_iteration

Taken from wiki:

   low = 0
   high = N
   while (low < high) {
       mid = low + ((high - low) / 2)
       if (A[mid] < value)
           low = mid + 1;
       else
            //can't be high = mid-1: here A[mid] >= value,
            //so high can't be < mid if A[mid] == value
            high = mid;
   }
   // high == low, using high or low depends on taste
   if ((low < N) && (A[low] == value))
       return low // found
   else
       return -1 // not found

Pros/cons from wiki: "This approach foregoes the possibility of early termination on discovery of a match, thus successful searches have log2(N) iterations instead of an expected log2(N) − 1 iterations. On the other hand, this implementation makes fewer comparisons: log2(N) is less than the expected number of comparisons for the two-test implementations of 1·5(log2(N) − 1), for N greater than eight."

like image 108
Lasse Espeholt Avatar answered Sep 22 '22 15:09

Lasse Espeholt