二分法基本上学计算机的都听过,但是有人不知道的就是其实二分法是减治法的思想。

所谓减治法和分治法有一个主要差别就是减治法是减去一般,就是分治之后只需要解决原问题的一半就可以了得到全局问题的解了。所以速度很快。

下面是二分法的递归程序和非递归程序和主测试程序:

#include<iostream>
#include<vector>
using namespace std; template<typename T>
int recurBiSearch(const vector<T> &vt, T key, int low, int up)
{
if(low>up) return -1;
int mid = (low+up)>>1;
if (key < vt[mid])
{
return recurBiSearch(vt, key, low, mid-1);
}
else if (vt[mid] < key)
{
return recurBiSearch(vt, key, mid+1, up);
}
return mid;
} template<typename T>
int iterBiSearch(vector<T> &vt, T key, int low, int up)
{
int mid;
while (low<=up)
{
mid = (low+up)>>1;
if(key<vt[mid])
up = mid - 1;
else if(vt[mid]<key)
low = mid + 1;
else return mid;
}
return -1;
} int main()
{
std::vector<int> vec; // set some initial content:
for (int i=1;i<10;i++) vec.push_back(i<<2); vec.resize(7);
vec.resize(12,80); std::cout << "vec contains:";
for (int i=0;i<vec.size();i++)
std::cout << ' ' << vec[i];
std::cout << '\n'; //二分法特征:这里vec.size()-1和不减1都是可以的。
cout<<"Recurrence Search Index Position: ";
int ind = recurBiSearch(vec, 20, 0, vec.size()-1);
cout<<ind;
cout<<"\tValue: "<<vec[ind]<<endl; cout<<"Iterative Search Index Position: ";
ind = iterBiSearch(vec, 20, 0, vec.size()-1);
cout<<ind;
cout<<"\tValue: "<<vec[ind]<<endl; system("pause");
return 0;
}

运行结果:

Binary Search二分法搜索C++程序-LMLPHP

04-26 20:03