二分查找主要有三点需要注意:
1、边界问题
2、求中点时的溢出问题
3、有重复值时定位第一个
代码如下:
int BinarySearch(int array[], int n, int v) { int left, right, middle; left = -1, right = n; while (left + 1 != right) { middle = left + (right - left) / 2; if (array[middle] < v) { left = middle; } else { right = middle; } } if (right >= n || array[right] != v) { right = -1; } return right; }
原文地址:http://blog.csdn.net/wwwdongzi/article/details/38982093