二分查找之用zy大佬的方法

遇到老师留的作业中要求用二分查找查找元素,因为对piviot中轴的位置没有判断清楚,就各种犯错
下面是zy大佬给的代码:(用c➕➕写的代码)
用二分的条件必须要求数组是排好序的

#include<iostream>
#define N 5
using namespace std;
int main()
{
	long long a[N],x,i,front,mid,end;
	cout<<"import the number group"<<endl;
	for(i=0;i<N;i++)//数组最好是从0开始
	{
		cin>>a[i];
	}
	cout<<"import x"<<endl;
	cin>>x;
	front=0;end=N-1;mid=(front+end)/2;
	while(front<end&&a[mid]!=x)
	{
		if(a[mid]<x)
		front=mid+1;
		if(a[mid]>x)
		end=mid-1;
		mid=(front+end)/2;
	}
	if(a[mid]!=x)
	{
		cout<<"NO this number"<<endl;
	}else{
		cout<<"in "<<mid+1<<endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值