首页 > 代码库 > 折半查找

折半查找

#include<iostream>using namespace std;int main(){    int a[10]={1,2,3,4,5,21,34,45,115,4121};    int f,tail=0,top=9,mid=(top+tail)/2;    int n;    cout<<"请输入要查找的数:"<<endl;    cin>>n;    while(1)    {        if(n==a[mid])        {            cout<<"yes!!!\n";            break;        }        else if(n<a[mid-1])        {            tail=tail;            top=mid-1;            mid=(top+tail)/2;        }        else        {            top=top;            tail=mid+1;            mid=(top+tail)/2;        }        if (tail>top)        {            cout<<"No!!!\n";            break;        }    }   return 0;}

 

折半查找