At the same time find the maximum and minimum

Topic Definition:

    Given an array of size n, random, find the maximum and minimum values ​​wherein the number of comparisons between the required elements as small as possible.

This question is from the "Introduction to Algorithms." Innovation Works 2016 school recruit written exam This question also.

The following excerpt from "Introduction to Algorithms":

    In fact, we need only the most 3⌊n / 2⌋ comparisons to find minimum and maximum values ​​simultaneously. Specific methods are known in the recording maximum and minimum values ​​of the input element then processed in pairs. First of all, we have a pair of input elements are compared with each other, then the smaller the current minimum value is compared with the current maximum of the greater of comparison. Thus, the comparison of the total of three times every two elements.

    How to set the initial value of the known minimum and maximum values depend on the n is odd or even. If n is odd, we will be minimum and maximum values are set to the initial value of the first element, and the remaining processing element pairs. If n is even, the first two elements to make a comparison to determine the minimum and maximum values of initial values, and then the same odd number n, the processing elements of the remaining pairs.

Posted about my code:

int min;
int max;
void findMinMax(int arr[], int n, int &min, int &max)
{
    int begin = 0;
    if (n % 2 == 1)
    {
        min = max = arr[0];
        begin = 1;
    }
    else
    {
        if (arr[0] < arr[1])
        {
            min = arr[0];
            max = arr[1];
        } 
        else
        {
            min = arr[1];
            max = arr[0];
        }
        begin = 2;
    }

    for (int i = begin; i < n-1; i = i+2)
    {
        if (arr[i] < arr[i+1])
        {
            if (arr[i] < min)
                min = arr[i];
            if (arr[i+1] > max) 
                max = arr[i+1];
        } 
        else
        {
            if (arr[i+1] < min)
                min = arr[i+1];
            if (arr[i] > max)
                max = arr[i];
        }
    }
}

 

Reproduced in: https: //www.cnblogs.com/gattaca/p/4814365.html

Guess you like

Origin blog.csdn.net/weixin_34324081/article/details/93401865