现在的位置: 首页 > 综合 > 正文

二分搜索法

2013年01月23日 ⁄ 综合 ⁄ 共 670字 ⁄ 字号 评论关闭

二分搜索法(C++)

#include <iostream.h>
int binarySearch(int a[] ,int x,int n);//函数声明

void main()
{

cout<<"\n-----------------二分搜索法----------";

int n;
cout<<"enter the values of n:\n";
cin>>n;
int b[6];//  *注意数组的初始化
cout<<"please enter the values of b["<<n<<"](from small to big )\n";
for(int j=0;j<n;j++)
{
cin>>b[j];
}
for(int p=0;p<n;p++)
{
cout<<b[p]<<"\t";
}
cout<<endl;
cout<<"enter the the value of which you want to search:\n";

int x;
cin>>x;

int e=binarySearch(b,x,n)+1;//函数调用   ,* 注意数组的调用
cout<<e<<endl;
}

int binarySearch(int a[],int x,int n)//函数定义
{
//在依大小次序排的数组a[n]中检索x,找到时返回它的位置
int left=0;int right=n-1;
while(left<=right)
{int middle=(left+right)/2;
if(x==a[middle]) return middle;
if(x>a[middle]) left=middle+1;
else right=middle-1;
}
return -1;
}

抱歉!评论已关闭.