算法思想:先相邻两个两个比较,较大的放入数组max[],较小的放入数组min[],然后从max[]数组求出最大,min[]数组求出最小即可。
比较n+[(n+1)/2] =1.5n次
1#include <iostream>
2#define n 11
3#define m ((n+1)/2)
4using namespace std;
5
6void main(void)
7{
8 int num[] = {11,2,3,4,6,5,7,8,9,10,20};
9 //int n = sizeof(num)/sizeof(num[0]);
10 //int m = (n+1)/2;
11 int max[m] , min[m];
12 int k = 0, j = 0;
13
14 if(n/2 != 0) max[m-1] = min[m-1] = num[n-1];
15
16 for (int i=0; i < n-1; i = i+2)
17 {
18 if (num[i] >= num[i+1])
19 {
20 max[j++] = num[i];
21 min[k++] = num[i+1];
22 }
23 else
24 {
25 max[j++] = num[i+1];
26 min[k++] = num[i];
27 }
28
29 }
30
31 for( i=0; i< m; i++)
32 {
33 cout << "max[" << i << "] = " << max[i] << "\t";
34 cout << "min[" << i << "] = " << min[i] <<endl;
35 }
36
37 int MAX = max[0];
38 int MIN = min[0];
39
40 for ( j = 1; j < m; j++)
41 {
42 if (max[j] > MAX) MAX = max[j];
43 if (min[j] < MIN) MIN = min[j];
44 }
45
46 cout << "MAX = " << MAX << ", MIN = " << MIN <<endl;
47}