二分查找主要有三点需要注意:
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; }
时间: 2024-11-08 17:17:56