假定输入数组已按递增序排序,查找整数x,代码如下:
int binary_search(int *array, int size, int x) {
int head = 0, tail = size - 1;
int mid;
while (head <= tail) {
mid = (head + tail) / 2;
if (array[mid] < x) {
head = mid + 1;
} else if (array[mid] > x) {
tail = mid - 1;
} else {
return mid;
}
}
return -1;
}