- 顺序表
- 有序
- log(n)
int binarySearch(int arr[], int len, int key)
{
int left = 0;
int right = len - 1;
int mid;
while (left <= right) { // 注意是<=
mid = (right - left) / 2 + left; // 防止溢出
if (key < arr[mid]) { // key在左边
right = mid - 1;
} else if (arr[mid] < key) { // key在右边
left = mid + 1;
} else {
return mid;
}
}
return -1;
}