|
|
|
@ -0,0 +1,65 @@
|
|
|
|
|
#include<iostream>
|
|
|
|
|
using namespace std;
|
|
|
|
|
|
|
|
|
|
#define OK 1
|
|
|
|
|
#define ERROR 0
|
|
|
|
|
#define MAXSIZE 100
|
|
|
|
|
|
|
|
|
|
typedef int KeyType;
|
|
|
|
|
typedef struct
|
|
|
|
|
{
|
|
|
|
|
int elem[MAXSIZE];
|
|
|
|
|
int length;
|
|
|
|
|
}SSTable; //建立一个顺序表来存放元素
|
|
|
|
|
|
|
|
|
|
int Search_Bin(SSTable ST,KeyType key)
|
|
|
|
|
{
|
|
|
|
|
int low,high,mid;
|
|
|
|
|
low=1;
|
|
|
|
|
high=ST.length;
|
|
|
|
|
while(low<=high)
|
|
|
|
|
{
|
|
|
|
|
mid=(low+high)/2; //折半,并且输出比较的元素
|
|
|
|
|
cout<<" "<<ST.elem[mid];
|
|
|
|
|
if(ST.elem[mid]==key)
|
|
|
|
|
return mid;
|
|
|
|
|
else if(ST.elem[mid]>key) //如果关键字大于查找的数字,则往小的移动
|
|
|
|
|
high=mid-1;
|
|
|
|
|
else if(ST.elem[mid]<key) //如果关键字大于查找的数字,则往大的移动
|
|
|
|
|
low=mid+1;
|
|
|
|
|
}
|
|
|
|
|
return -1;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
int main()
|
|
|
|
|
{
|
|
|
|
|
SSTable ST;
|
|
|
|
|
KeyType n;
|
|
|
|
|
int a;
|
|
|
|
|
cout<<"请输入有序表的长度:"<<endl;
|
|
|
|
|
cin>>ST.length;
|
|
|
|
|
cout<<"请输入有序表的元素"<<endl;
|
|
|
|
|
for(int i=1;i<=ST.length;i++)
|
|
|
|
|
{
|
|
|
|
|
cin>>ST.elem[i];
|
|
|
|
|
}
|
|
|
|
|
cout<<"请输入要查找的元素:"<<endl;
|
|
|
|
|
cin>>n;
|
|
|
|
|
cout<<"比较的元素有:";
|
|
|
|
|
a=Search_Bin(ST,n);
|
|
|
|
|
if(a>=0)
|
|
|
|
|
cout<<"\n查找元素的下标是:"<<a<<endl;
|
|
|
|
|
else
|
|
|
|
|
cout<<"在有序表中未找到您想查找到元素!"<<endl;
|
|
|
|
|
}
|
|
|
|
|
/*
|
|
|
|
|
请输入有序表的长度:
|
|
|
|
|
11
|
|
|
|
|
请输入有序表的元素
|
|
|
|
|
05 13 19 21 37 56 64 75 80 88 92
|
|
|
|
|
请输入要查找的元素:
|
|
|
|
|
21
|
|
|
|
|
比较的元素有: 56 19 21
|
|
|
|
|
查找元素的下标是:4
|
|
|
|
|
|
|
|
|
|
*/
|