#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;
}
簡單折半算法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.