静态查找表
#include<stdio.h>
#include<iostream>
#include<malloc.h>
using namespace std;
typedef int KeyType;
typedef struct
{
KeyType key;
}ElemType;
typedef struct
{
ElemType *elem;
int length;
}Stable;
void Create(Stable &ST,int n) // 建立静态查找表
{
ST.elem=(ElemType *)malloc((n+1)*sizeof(ElemType));
ST.length=n;
for(int i=1;i<=n;i++)
cin>>ST.elem[i].key;
}
int Search(Stable &ST,KeyType key) //顺序表的查找
{
int i=ST.length;
ST.elem[0].key=key;
while(ST.elem[i].key!=key)
i--;
return i;
}
int SearchBin(Stable &ST,KeyType key) //有序表的查找(折半查找)
{
int low,high,mid;
low=1;
high=ST.length;
while(low<=high)
{
mid=(low+high)/2;
if(ST.elem[mid].key==key) return mid;
else if(ST.elem[mid].key>key) high=mid-1;
else low=mid+1;
}
}
int main()
{
Stable ST;
KeyType k;
int n;
cin>>n;
Create(ST,n);
cin>>k;
/*if(Search(ST,k)==0) cout<<"没有找到"<<endl;
else cout<<Search(ST,k)<<endl;
*/
if(SearchBin(ST,k)==0) cout<<"没有找到"<<endl;
else cout<<SearchBin(ST,k)<<endl;
return 0;
}