因为发现stl里面带了binary_search,以后可以不用给自己写了,怕自己不会写,所以自己先实现了一个二分查找。
我的这个二分查找不是返回true和false,而是返回iterator,当查找不到的时候,返回end()
#include <iostream>
#include <vector>
using namespace std;
template <class BidirectionIterator, class T>
BidirectionIterator binary_search(BidirectionIterator begin, BidirectionIterator end, T target) {
BidirectionIterator mid, end_reserve = end, last_mid;
mid = begin + (end-begin)/2;
while(begin != end && mid != last_mid) {
if(*mid == target) {
return mid;
}
else if(*mid > target) {
end = mid;
mid = begin + (end-begin)/2;
}
else {
begin = mid;
mid = begin + (end-begin)/2;
}
last_mid = mid;
}
return end_reserve;
}
int main() {
vector<int> v{1,2};
vector<int>::iterator itr;
itr = binary_search(v.begin(),v.end(), 3);
if(itr != v.end()) {
cout << "Found and the position is " << itr - v.begin() << endl;
}
else{
cout << "Not found!" << endl;
}
}