码迷,mamicode.com
首页 > 其他好文 > 详细

二分查找

时间:2017-01-12 11:07:33      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:递归   return   tchar   class   names   vector   turn   else   clu   

#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;
}

 

二分查找

标签:递归   return   tchar   class   names   vector   turn   else   clu   

原文地址:http://www.cnblogs.com/kaishan1990/p/6275095.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!