C++二分法查找算法

/**************************************************************
* 二分法查找算法
* wxz 2011-05-04
***************************************************************/
#include<iostream>
#define MaxSize 100
using namespace std;
typedef int DataType;

typedef struct ST
{
DataType Data[MaxSize];
int Length;
}ST;

void CreateST(ST *st)
{
int i;
cout<<"请输入要建立的顺序表的长度"<<"("<<MaxSize<<"以内)"<<endl;
cin>>st->Length;
while(st->Length>100)
{
cout<<"长度不能大于"<<MaxSize<<endl;
cout<<"请输入要建立的顺序表的长度"<<"("<<MaxSize<<"以内)"<<endl;
cin>>st->Length;
}
cout<<"请输入"<<st->Length<<"个整数:"<<endl;
for(i=0;i<=st->Length-1;i++)
cin>>st->Data[i];

}

int BinarySearch(ST *st,DataType d)
{
int low,high,mid;
int count;
int flag;
low=0;
count=1;
flag=0;
high=st->Length-1;
while(low<=high)
{
mid=(low+high)/2;
if (d<st->Data[mid])
high=mid-1;
else
if(d>st->Data[mid])
low=mid+1;
else
{
flag=mid;
break;
}
count++;

}

return flag;
}
int main()
{
int idx;
DataType d;
ST *st=new ST;
CreateST(st);
cout<<"请输入要查找的元素:";
cin>>d;
idx=BinarySearch(st,d)+1;
if(idx==0)
cout<<"没有找到你要查找的元素。";
else
cout<<"所要查找的元素"<<d<<"的位置是"<<idx<<endl;
return 0;
}

 

 

你可能感兴趣的:(算法)