5、折半查找(二分查找)


前提条件:数组排序

  1 #include<iostream>
  2 
  3 using namespace std;
  4 
  5 int BinarySearch(int *a,const int x,const int n);
  6 
  7 int main()
  8 {
  9 	int x[]={1,2,3,4,5,6,7,8,9,10};
 10 	int result;
 11 	int num=7;//要找的数
 12 	result=BinarySearch(x,num,10);
 13 
 14 	if(result<0)
 15 		cout<<”没找到!”<<endl;
 16 	else
 17 		cout<<"在m["<<result<<"]处找到"<<x[result]<<endl;
 18 	system("pause");
 19 	return 0;
 20 }
 21 
 22 int BinarySearch(int *a,const int x,const int n)
 23 {
 24 	int left,right,mid;
 25 	left=0;right=n-1;
 26 
 27 	while(left<=right)
 28 	{
 29 		mid=(left+right)/2;
 30 		if(a[mid] == x)
 31 			return mid;
 32 		else if(a[mid] < x)
 33 			left=mid+1;
 34 		else if(a[mid] > x)
 35 			right=mid-1;
 36 	}
 37 	return -1;
 38 }
 39 

VS2010中运行结果:

image

转载于:https://www.cnblogs.com/luanxin/p/8875054.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值