二分查找,又名折半查找,是一种对于搜索的优化算法
对于大量的数据,如果用普通的暴力搜索就显得非常浪费时间
只要有一个数据就要尝试一次 非常麻烦
于是有一个瓜皮发明出了这样一种算法:
对于一组有序的数据,
找出这组数据的中点,判断要找的数据在它的前边还是后边
这样就能排除一半的数据;
然后把这个中点设为数据的起点或终点(刨除不包含目标的数据)
再找中点,再比较
如此循环往复,能节省一半的时间
妙啊
于是有了如下的代码:
while(h<=m)
{
m=(h+e)/2;
if(seq[m]==tosearch)
{
cout<<"Found match:At No."<<m<<endl;
return 0;
}
else if(seq[m]<tosearch)
{
h=m;
}
else if(seq[m]>tosearch)
{
e=m;
}
}
cout<<"Not match found"<<endl;
这种算法的优点显而易见,省时省空间
但缺点也很明显,它查找的数据必须是有序的
必须能判断中点在目标值的前边或者后边
但大部分数据都不是这样
所以在使用折半查找之前必须先排序
于是完整代码成了这样
#include<bits\stdc++.h>
using namespace std;
int main()
{
//definition
int seq[100],i,n,tosearch;
int h,e,m,temp;
//input
cout<<"Please Enter ammount of array"<<endl;
cin>>n;
cout<<"Please Enter the array"<<endl;
for(i=0;i<n;i++)
cin>>seq[i];
//sort
for(int i=0;i<n-1;i++)
{
for(int j=n-1;j>i;j--)
{
if(seq[j]>seq[j-1])
{
temp=seq[j];
seq[j]=seq[j-1];
seq[j-1]=temp;
}
}
}
h=0;
e=n-1;
//input integer to search
cout<<"Please enter a integer to search."<<endl;
cin>>tosearch;
//procession
while(h<=m)
{
m=(h+e)/2;
if(seq[m]==tosearch)
{
cout<<"Found match:At No."<<m<<endl;
return 0;
}
else if(seq[m]<tosearch)
{
h=m;
}
else if(seq[m]>tosearch)
{
e=m;
}
}
cout<<"Not match found"<<endl;
return 0;
}