折半查找

main
柊叶 1 year ago
parent 1df9091936
commit f607150570

@ -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
*/
Loading…
Cancel
Save