Skip to content

Instantly share code, notes, and snippets.

@zhpengg
Created December 13, 2011 09:55
Show Gist options
  • Save zhpengg/1471458 to your computer and use it in GitHub Desktop.
Save zhpengg/1471458 to your computer and use it in GitHub Desktop.
binary search in cpp
#include <iostream>
#include <vector>
using namespace std;
template <typename t>
typename vector<t>::iterator mbsearch(vector<t> &haystack, t key)
{
typename vector<t>::iterator left, middle, right;
left = haystack.begin();
right = haystack.end();
while (left <= right) {
middle = left + (right - left) / 2;
if (*middle == key) {
return middle;
} else if (*middle < key) {
left = middle + 1;
} else {
right = middle - 1;
}
}
return haystack.end();
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
vector<int> vi(arr, arr+9);
vector<int>::iterator pos = mbsearch(vi, 6);
if (pos != vi.end()) {
cout << "find:" << *pos << endl;
} else {
cout << "not find." << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment