首页 > 其他 > 详细

binary search

时间:2016-02-20 07:01:57      阅读:210      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!