#include<iostream>
#define maxsize 100
using namespace std;
typedef struct{
int list[maxsize];
int length;
}Table;
int binarysearch(Table T,int x);
int main(){
Table T={{12,14,45,21,76,26,34,99},8};
int i,find,x;
cout<<"有序顺序表的元素:";
for(i=0;i<T.length;i++)
cout<<T.list[i]<<" ";
cout<<endl;
cout<<"请输入要查找的元素:";
cin>>x;
find=binarysearch(T,x);
if (find)
cout<<"元素"<<x<<"是第"<<find<<"个元素"<<endl;
else cout<<"error!";
return 0;
}
int binarysearch(Table T,int x)
{
int low,high,mid;
low=0;high=T.length-1;
while(low<=high)
{
mid=(low+high)/2;
if(T.list[mid]==x)
return mid+1;
else if (T.list[mid]<x)
low=mid+1;
else if(T.list[mid]>x)
high=mid-1;
}
return 0;
}
简单折半算法
猜你喜欢
转载自blog.csdn.net/agoodboy1997/article/details/82156460
今日推荐
周排行