C++ implements an example algorithm to extract the maximum and minimum elements from an array at the same time

  • 2020-05-30 20:35:31
  • OfStack

This article demonstrates an example of how C++ can extract the largest and smallest elements from an array at the same time. I will share it with you for your reference as follows:

Algorithm idea: first, two adjacent two comparison, the larger into the array max[], the smaller into the array min[], and then from the max[] array to find the largest, min[] array to find the smallest.

Compare n+[(n+1)/2] =1.5n times


#include <iostream>
#define n 11
#define m ((n+1)/2)
using namespace std;
void main(void)
{
  int num[] = {11,2,3,4,6,5,7,8,9,10,20};
  //int n = sizeof(num)/sizeof(num[0]);
  //int m = (n+1)/2;
  int max[m] , min[m];
  int k = 0, j = 0;
  if(n/2 != 0) max[m-1] = min[m-1] = num[n-1];
  for (int i=0; i < n-1; i = i+2)
  {
    if (num[i] >= num[i+1])
    {
      max[j++] = num[i];
      min[k++] = num[i+1];
    }
    else
    {
      max[j++] = num[i+1];
      min[k++] = num[i];
    }
  }
  for( i=0; i< m; i++)
  {
    cout << "max[" << i << "] = " << max[i] << "\t";
    cout << "min[" << i << "] = " << min[i] <<endl;
  }
  int MAX = max[0];
  int MIN = min[0];
  for ( j = 1; j < m; j++)
  {
    if (max[j] > MAX) MAX = max[j];
    if (min[j] < MIN) MIN = min[j];
  }
  cout << "MAX = " << MAX << ", MIN = " << MIN <<endl;
}

I hope this article is helpful to you C++ programming.


Related articles: