You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#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
*/