Design an optimal algorithm to find the maximum and minimum values in an array of n elements

Topic description

There is an algorithm to find the maximum and minimum values ​​of an array of n elements, which requires 2n comparisons; please write a most efficient algorithm and specify the number of comparisons. Please pay attention to the constant of complexity
(you don't need to write code, just explain the steps and processes, you need to set the number of comparisons, no points will be given if you don't write it)

Problem solving ideas

First traverse the array, divide the two into a group, put the small one on the left and the big one on the right, so that the number of comparisons is N/2. N is the length of the array. Then the smallest element must be on the left of each group and the largest element on the right. The next step is to compare all the elements on the left N/2 times to produce the smallest, and to compare the elements on the right N/2 times to produce the largest. The total number of comparisons required is 3*(N/2) times.

implementation code

#include <iostream>
#include "limits.h"
using namespace std;

int main() {
    int d[] = {9, 6, 7, 5, 13, 6, 2};
    int n = 8;
    int max = INT_MIN;
    int min = INT_MAX;
    bool flag = false;
    if(n % 2) {
        n--;
        flag = true;        
    }   
    for(int i = 0; i < n-1; i+=2) {
        if(d[i] <= d[i+1]) {
            if(d[i] < min)
                min = d[i];
            if(d[i+1] > max)
                max = d[i+1];
        }
        else {
            if(d[i] > max)
                max = d[i];
            if(d[i+1] < min)
                min = d[i+1];
        }   
    }
    //若数组长度为奇数,还需要和最后一个数作比较 
    if(flag) {
        if(d[n] < min)
            min = d[n];
        if(d[n] > max)
            max = d[n]; 
    }
    cout << "The max value of the array is: " << max << endl;
    cout << "The min value of the array is: " << min << endl;   
} 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325599877&siteId=291194637