二分查找
进行二分查找的前提是序列已经有序,二分查找的时间复杂度为O(lgn)。每次和中间的数字进行比较,如果比较的数比中间的大,就在右边查找,小就在左边查找。
具体实现
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int binary_search(vector<int>& vec, int start, int end, int value) {
if (start > end) {
return -1;
}
int middle = (start + end) / 2;
if (value == vec[middle]) {
return middle;
} else if (value < vec[middle]) {
return binary_search(vec, start, middle - 1, value);
} else if (value > vec[middle]) {
return binary_search(vec, middle + 1, end, value);
}
}
};
int main() {
int arr[] = {1, 2, 2, 3, 4, 5, 6, 7, 7, 100};
vector<int> vec(arr, arr+10);
Solution* solution = new Solution();
cout << solution->binary_search(vec, 0, 9, 100) << endl;
return 0;
}