本文实例讲述了C++实现从数组中同时取出最大最小元素的方法。分享给大家供大家参考,具体如下:
算法思想:先相邻两个两个比较,较大的放入数组max[],较小的放入数组min[],然后从max[]数组求出最大,min[]数组求出最小即可。
比较n+[(n+1)/2] =1.5n次
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
#include <iostream>
#define n 11
#define m ((n+1)/2)
using namespace std;
void main( void )
{
int num[] = {11,2,3,4,6,5,7,8,9,10,20};
//int n = sizeof(num)/sizeof(num[0]);
//int m = (n+1)/2;
int max[m] , min[m];
int k = 0, j = 0;
if (n/2 != 0) max[m-1] = min[m-1] = num[n-1];
for ( int i=0; i < n-1; i = i+2)
{
if (num[i] >= num[i+1])
{
max[j++] = num[i];
min[k++] = num[i+1];
}
else
{
max[j++] = num[i+1];
min[k++] = num[i];
}
}
for ( i=0; i< m; i++)
{
cout << "max[" << i << "] = " << max[i] << "\t" ;
cout << "min[" << i << "] = " << min[i] <<endl;
}
int MAX = max[0];
int MIN = min[0];
for ( j = 1; j < m; j++)
{
if (max[j] > MAX) MAX = max[j];
if (min[j] < MIN) MIN = min[j];
}
cout << "MAX = " << MAX << ", MIN = " << MIN <<endl;
}
|
希望本文所述对大家C++程序设计有所帮助。
原文链接:http://www.cnblogs.com/liyuxia713/archive/2009/04/14/2540783.html