数据结构_折半查找

来源:互联网 发布:软件操作说明书模版 编辑:程序博客网 时间:2024/05/02 00:37
#include <iostream>#include <cstdio>#include <cstring>using namespace std;#include <algorithm>typedef int ElemType;typedef struct Node{    int id;    ElemType data;}A;A a[100];bool cmp(A a,A b){    return a.data<b.data;}void Init(int n){    for(int i=0;i<n;i++)    {        a[i].id=i+1;        a[i].data=0;    }}int Find(int low,int high, ElemType e){    int mid=(low+high)/2;    while(low<=high)    {        if(a[mid].data>e) high=mid-1;        else if(a[mid].data<e) low=mid+1;        else return mid;        mid=(low+high)/2;    }    return -1;}int main(){    cout << "输入的个数:" << endl;    int n;    cin>>n;    Init(n);    cout<<"请依次输入各个元素:"<<endl;    for(int i=0;i<n;i++)    {        cin>>a[i].data;    }     sort(a,a+n,cmp);     //for(int i=0;i<n;i++)       // cout<<a[i].id<<endl;    cout<<"查找的次数:"<<endl;    int k;    cin>>k;    while(k--)    {        ElemType e;        cout<<"输入要查询的数字:"<<endl;        cin>>e;        int lo=Find(0,n-1,e);        if(lo==-1)            cout<<"查询的元素不在序列中"<<endl;        else            cout<<"查询的元素 "<<e<<" 在 "<<a[lo].id<<" 处"<<endl;    }    return 0;}

0 0