码迷,mamicode.com
首页 > 其他好文 > 详细

binary search

时间:2016-02-20 07:03:12      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

binary search

标签:

原文地址:http://www.cnblogs.com/charmingblog/p/5202590.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!