二分查找

#include<iostream>
using namespace std;
int binsearch(int a[],int low,int high,int k)
{
    if(low>high) return 0;
    int mid=(low+high)/2;
    if(a[mid]==k)
           return mid+1;
    else if(a[mid]<k)
           return binsearch(a,mid+1,high,k);
    else
           return binsearch(a,low,mid-1,k);
}
int main()
{
    int a[100];
    int len;
    cout<<"len=";
    cin>>len;
    cout<<"a[i]:\n";
    for(int i=0;i<len;i++)
        cin>>a[i];
    while(1)
    {
    int k;
    cout<<"k=";
    cin>>k;
    cout<<binsearch(a,0,len-1,k)<<endl;
    } 
    return 0;
 } 

 

posted @ 2018-12-04 15:16  shenyuli  阅读(119)  评论(0编辑  收藏  举报
Live2D