#include <iostream>
#include <vector>
using std::cout;
using std::endl;
template <typename T>
int binary_search(const std::vector<T>& list, const int& item) {
int low = 0;
int high = list.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
T guess = list[mid];
if (guess == item) {
return mid;
}
if (guess > item) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
// this function returns pointer to the found element rather than array index
template <typename T>
const T* binary_search2(const std::vector<T>& list, const T& item) {
const T* low = &list.front();
const T* high = &list.back();
while (low <= high) {
// "guess" is the element in the middle between "high" and "low"
二分查找cpp
最新推荐文章于 2024-04-10 13:54:28 发布