中间数查找

/*
	在一个int数组里查找这样的数,它大于等于左侧所有数,小于等于右侧所有数。
//*/
#include <iostream>
#include <iomanip>
#include <limits>

using namespace std;

// 找到第一个满足要求的中间数『将满足要求的数成为中间数』
int main()
{
	int numel[] = {15, 12, 34, 27, 46, 76, 53, 121, 67, 85, 137, 145,103, 183};
	int sz = sizeof(numel)/sizeof(numel[0]);
	int pos = 1;
	int med = 0;  // 假设满足条件的中间数在首位,其左边没有数,满足大于左边的要求

	while(pos < sz -1){
		while((numel[pos] >= numel[med]) && (pos < sz -1)){  //如果右边的数大于左边的数,那么继续递增
			++pos;
		}
		if(pos == sz-1){  // 如果pos==sz-1; 遍历结束,说明numel[med]小于其右边所有的数!
			break;
		}else{ 
			// 向右遍历过程中遇到比中间数小的数,那么继续向右遍历,直到遇到第一个比中间数大的数,
			// 将这个数赋给中间数,那么中间数必定大于其左边的所有数
			while((numel[pos] <= numel[med]) && (pos < sz -1)){
				++pos;
			}
			if(pos <= sz -1 && numel[pos] > numel[med]){ 
				med = pos;
			}else{ // 越界或者没找到则输出错误信息并返回
				cout << "no such number!\n"; 
				return -1;
			}
		}
	}

	cout << numel[med] << endl;
	

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值