二分查找

#include <iostream>

using namespace std;

//常规方式
int binary_find(vector<int> &data, int num)
{
int low = 0;
int high = data.size() - 1;

while (low <= high) {
int mid = low + (high - low) / 2;
if (num == data[mid]) {
return mid;
} else if (num < data[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}    
}

return -1;
}

//递归方式
int binary_find(vector<int> &data, int low, int high, int num)
{
if (low > high) return -1;

int mid = low + (high - low) / 2;
if (num == data[mid]) {
return mid;
}
else if (num < data[mid]) {
binary_find(data, low, mid - 1, num);
}
else {
binary_find(data, mid + 1, high, num);
}
}

int main()
{
int a[] = {1, 2, 3, 4, 6, 7, 8, 9, 100, 10000};
vector<int> test_vector(a, a+10);
int i = binary_find(test_vector, 10000);
cout << i << endl;
getchar();

return 0;
}

 

posted @ 2017-01-11 20:34  略加思索的河马  阅读(136)  评论(0编辑  收藏  举报