//二分法查找
#include <stdio.h>
#include <iostream.h>
#include <malloc.h>
typedef struct sstable
{
int a[100];
int length;
}sstable;
void chushihua(sstable &l)
{
l.length=0;
}
void fuzhi(sstable &l)
{
int i=0;
cout<<"请输入有序表:";
while(1)
{
cin>>l.a[i];
if(l.a[i]<0)
break;
else{l.length++;i++;}
}
}
int searchkey(sstable ss,int key)
{
int low,mid,high;
low=0;
high=ss.length;
while(low<=high)
{
mid=(low+high)/2;
if(ss.a[mid]==key)
return mid;
else if(ss.a[mid]>key)
high=mid-1;
else low=mid+1;
}
return 0;
}
void main()
{
sstable ss;
int i,n,key;
chushihua(ss);
fuzhi(ss);
cout<<"输入要查找的元素"<<endl;
cin>>key;
i=searchkey(ss,key);
if(i)
cout<<key<<"在有序表中第"<<i+1<<"位。"<<endl;
else cout<<"在有序表中未查找到元素"<<key<<endl;
}