寻找数组中的最大值和最小值(编程之美2.10,包括最大值和次大值)
2010-09-23 19:31
399 查看
// 2_9.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <cassert> #define INT_MIN -100000 //最大值和最小值 void min_max(int * arr, size_t len, int & min, int &max) { assert(arr); assert(len>0); int start = 0; if(len%2 ==0) { if(arr[0]>arr[1]) { min=arr[1]; max=arr[0]; } else { min=arr[0]; max=arr[1]; } start=2; } else { min=arr[0]; max=arr[1]; start = 1; } for(;start<len;start+=2) { if(arr[start]>arr[start+1]) { if(arr[start]>max) max = arr[start]; if(arr[start+1]<min) min = arr[start+1]; } else { if(arr[start+1]>max) max = arr[start+1]; if(arr[start]<min) min = arr[start]; } } } //最大值和次大值,递归实现 void max_secondMax(int * arr, int left, int right, int & max, int &max2) { if(right == left) { max = arr[left]; max2 = INT_MIN; return; } else if(right - left == 1) { if(arr[right] > arr[left]) { max = arr[right]; max2 = arr[left]; return; } else { max = arr[left]; max2 = arr[right]; return; } } int lmax, lmax2; int rmax, rmax2; max_secondMax(arr, left, left+(right-left)/2,lmax,lmax2); max_secondMax(arr, left+(right-left)/2+1, right,rmax,rmax2); if(lmax>rmax) { max = lmax; if(lmax2 > rmax) max2 = lmax2; else max2 = rmax; } else { max = rmax; if(rmax2 > lmax) max2 = rmax2; else max2 = lmax; } } int _tmain(int argc, _TCHAR* argv[]) { int arr[5] = {2,3,102,4,100}; int min,max; min_max(arr,5,min,max); printf("max:%d,min:%d\n",max,min); int max2; max_secondMax(arr,0,4,max,max2); printf("max:%d,second max:%d\n",max,max2); return 0; }
相关文章推荐
- 寻找数组中的最大值和最小值(编程之美2.10,包括最大值和次大值)
- 编程之美2.10 寻找数组中的最大值和最小值
- 编程之美2.10 寻找数组中的最大值和最小值
- 编程之美2.10 寻找数组中的最大值和最小值
- 寻找数组中的最大值和最小值(编程之美2.10)
- 编程之美2.10:寻找数组中的最大值和最小值
- 编程之美2.10 寻找数组中的最大值和最小值
- 编程之美2.10 寻找数组的最大值和最小值
- 寻找数组中的最小值和最大值——编程之美2.10
- 《编程之美》2.10 寻找数组中的最大值和最小值
- 编程之美2.10寻找数组中的最大值和最小值扩展问题Java版
- 编程之美2.10寻找数组中的最大值和最小值代码
- 编程之美2.10 寻找数组中的最大值和最小值
- [编程之美] PSet2.10 寻找数组中的最大值和最小值
- 编程之美_2.10_寻找数组中的最大值和最小值
- 编程之美-2.10-寻找数组中的最大值和最小值
- js同时寻找数组中最大值和最小值,编程之美解法三
- 读书笔记之编程之美 - 2.10 寻找数组中的最大值和最小值
- 《编程之美》学习笔记——2.10寻找数组中的最大值和最小值
- 编程之美:第二章 数字之魅 2.10寻找数组中的最大值和最小值