有序表的折半查找

有序表的折半查找
这里写图片描述

#include <iostream>
using namespace std;
typedef struct
{
    int r[100];
    int length;
}table;
int create(table &t)
{
    int a;
    t.length=0;
    cin>>a;
    while(a!=0)
    {
        t.r[t.length]=a;
        t.length++;
        cin>>a;
    }
    return 1;
}
int search_bin(table &t,int key)
{
    int low,high,mid;
    low=1;high=t.length;
    while(low<=high)
    {
        mid=(low+high)/2;
        if(key==t.r[mid]) return mid;
        else if(key<t.r[mid]) high=mid-1;
        else low=mid+1;
    }
    return 0;
}
int main()
{
    table t;
    int key,c;
    create(t);
    cin>>key;
    c=search_bin(t,key);
    cout<<c+1;
    return 0;
}



猜你喜欢

转载自blog.csdn.net/qq_37486501/article/details/80948093