/*
在一个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;
}
中间数查找
最新推荐文章于 2022-04-14 21:45:55 发布