binary search

The implementation of binary search is not complicated, but it is a vivid illustration of the power of divide-and-conquer.

Here is the code

 1 int binarySearch(int a[], int n, int x){
 2     int lo = 0;
 3     int hi = n-1;
 4     while(lo<=hi){
 5         int mid = lo + (hi-lo)/2;
 6         if (a[mid] == x) return mid;
 7         else if(a[mid]<x)
 8             lo = mid + 1;
 9         else hi = mid - 1;
10     }
11     return -1;  //not found;
12 }

Pay attention to line 5: we can't use 'mid = (lo+hi)/2' here. we may have over-flow if (lo+hi)>231 - 1.

More details about this subtle bug.

 

posted @ 2016-02-20 05:01  WithJiaJia  阅读(151)  评论(0)    收藏  举报