编程之美 - 寻找数组中的最大值和最小值

本文探讨编程中如何巧妙地找到数组中的最大值和最小值,通过第四种思路展示实现方法,涉及核心算法和系统输入处理。
摘要由CSDN通过智能技术生成

根据书中第四种思路得到下面的源码:

#include <iostream>
using namespace std;

struct mytype{//定义返回类型
	int x,y;
	mytype(int m,int n) : x(m),y(n){}
};

mytype Search(int arr[],int b,int e)
{
	int maxV,minV;
	if (e - b <= 1)
	{
		int max = arr[e] < arr[b] ? arr[b] : arr[e];
		int min = arr[e] < arr[b] ? arr[e] : arr[b];
		cout<<"..."<<max<<" ,"<<min<<"..."<<endl<<endl;

		return mytype(max,min);
	}

	mytype strL = Search(arr,b,(b + e) / 2);  //前半部分递归
	mytype strR = Search(arr,(b + e) / 2 + 1,e);//后半部分递归

	maxV = strL.x > strR.x ? strL.x : strR.x;//求max
	minV = strL.y < strR.y ? strL.y : strR.y;//求min
	return mytype(maxV,minV);
}

int main()
{
	cout << "input several numbers:" << endl;
	int b[100];
	int i = 0,j;
	while(cin >> j)
	{
		b[i] = j;
		i++;
	}
	cout << "the maxV and minV are:" << endl;
	mytype result = Search(b,0,i - 1);
	cout << "执行结果:" << result.x << " ," << result.y << endl;
	i = 0;
	system("pause");
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值