折半查找

来源:互联网 发布:node es6 编辑:程序博客网 时间:2024/05/29 09:07
#include<iostream>

using namespace std;

int MiddleSearch(int *l,const int n,int x)
{
    int low=0,high=n-1,mid;
    while(low<=high)
    {
        mid = (low+high)/2;
        {
        if(l[mid]==x)
            return mid;
        else if(l[mid]<x)
            low = mid + 1;
        else if(l[mid]>x)
            high = mid - 1;
        }
    }
    return -1;
}

void main()
{
    int l[8] = {1,2,4,5,6,7,8,9};
    int result,e;
    
    while(cin>>e)
    {
    result = MiddleSearch(l,8,e);
    if(result < 0)
        cout<<"未找到"<<endl;
    else
        cout<<e<<"是a["<<result<<"]"<<endl;
    }
}

1 0