编程之美2.10寻找数组中的最大值和最小值代码

P161 分治法求解,复杂度为f(N) = 1.5N-1;

代码如下:比较简单


#include 

using namespace std;

void FindMaxAndMin(int num[],int l,int r,int &minNum,int &maxNum);

int main()
{
    int n = 6;
    int num[] = {6,5,8,3,9,7};
    int minNum,maxNum;

    FindMaxAndMin(num,0,n-1,minNum,maxNum);
    for(int i=0 ; i num[l]){
            maxNum = num[r];
            minNum = num[l];
        }
        else{
            maxNum = num[l];
            minNum = num[r];
        }
        return ;
    }
    FindMaxAndMin(num,l,(l+r)/2,minl,maxl);
    FindMaxAndMin(num,1+(l+r)/2,r,minr,maxr);
    //merge
    if(minl < minr){
        minNum = minl;
    }
    else{
        minNum = minr;
    }
    if(maxl > maxr){
        maxNum = maxl;
    }
    else{
        maxNum = maxr;
    }

}



你可能感兴趣的:(编程之美,编程之美)