二分查找是一个比较简单的算法,用 C++ 语言实现如下:
template <typename T>
int binary_search(
const T& key, // 搜索元素 key
vector<int>::const_iterator data, // 数组起始位置
int N) // 元素个数
{
// 左闭右闭
int low = 0;
int high = N - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (key < *(data + mid))
high = mid - 1;
else if (key > *(data + mid))
low = mid + 1;
else
return mid;
}
return -1;
}
用法:
// vector<int> arr = {1, 2, 3, 4, 5, 65};
// cout << binary_search(5, arr.cbegin(), 6) << endl;
// cout << binary_search(1, arr.cbegin(), 6) << endl;
// cout << binary_search(4, arr.cbegin(), 6) << endl;