• 分治法求最大数最小数


     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 }
  • 相关阅读:
    C++实现多项式曲线拟合--polyfit-超定方程
    C# XmlDocument操作XML
    C#下使用XmlDocument详解
    前端常见的9种设计模式
    前端常用的设计模式
    前端需要了解的9种设计模式
    TCP协议详解
    请UI小姐姐喝了一杯奶茶要来的网站
    nodemon 基本配置与使用
    wireshark抓包新手使用教程
  • 原文地址:https://www.cnblogs.com/nothx/p/8578107.html
Copyright © 2020-2023  润新知