分治法求最大数最小数

 1 #include <stdio.h>
 2 /*
 3  * 任意十个数,打印出它们中的最大数、最小数
 4  *
 5  * 测试数据:①  1,-12,20,30,-5,-23,33,125,200,-100
 6               ②  0,10,3,1,5,6,-10,90,9,-4
 7               ③  12,13,14,15,10,-10,-11,-12,-9,9
 8     思路:用分治法的思想做
 9  * */
10 #define ARRY_SIZE 10
11 
12 void GetMaxAndMin(int *pArr, int l, int r, int *pMax, int *pMin);
13 
14 int main()
15 {
16     // 定义数组
17     //int iArr[ARRY_SIZE] = {12,13,14,15,10,-10,-11,-12,-9,9};
18     //int iArr[ARRY_SIZE] = {0,10,3,1,5,6,-10,90,9,-4};
19    int iArr[ARRY_SIZE] = {1,-12,20,30,-5,-23,33,125,200,-100};
20     int iMax, iMin;
21     GetMaxAndMin(iArr, 0, ARRY_SIZE - 1, &iMax, &iMin);
22     printf("The max value is %d
The min vlaue is %d
", iMax, iMin);
23     return 0;
24 }
25 
26 void GetMaxAndMin(int *pArr, int l, int r, int *pMax, int *pMin)
27 {
28     if (l == r)
29     {
30         *pMax = pArr[l];
31         *pMin = pArr[1];
32         return;
33     }
34     else if(l + 1 == r)
35     {
36         if (pArr[l] >= pArr[r])
37         {
38             *pMax = pArr[l];
39             *pMin = pArr[r];
40 
41         }
42         else
43         {
44             *pMax = pArr[r];
45             *pMin = pArr[l];
46         }//else
47         return;
48     }
49     int iMiddle = (l + r) / 2;  // 求中点
50     int lMax;
51     int lMin;
52     GetMaxAndMin(pArr, l, iMiddle, &lMax, &lMin);
53     int rMax;
54     int rMin;
55     GetMaxAndMin(pArr, iMiddle, r, &rMax, &rMin);
56     *pMax = lMax > rMax ? lMax : rMax;
57     *pMin = lMin > rMin ? rMin : lMin;
58 
59 
60 }
原文地址:https://www.cnblogs.com/nothx/p/8578107.html