Find the first, second and third minimum elements in an array in C++ program

C++Server Side ProgrammingProgramming

Suppose we have an array of n elements. We have to find the first, second and the third minimum elements in the array. First minimum is the minimum of the array, second min is minimum but larger than the first one, and similarly the third min is minimum but greater than second min.

Scan through each element, then check the element, and relate the condition for first, second and third min elements conditions to solve this problem.

Example

#include<iostream>
using namespace std;
int getThreeMins(int arr[], int n) {
   int first = INT_MAX, sec = INT_MAX, third = INT_MAX;
   for (int i = 0; i < n; i++) {
      if (arr[i] < first) {
         third = sec;
         sec = first;
         first = arr[i];
      } else if (arr[i] < sec) {
         third = sec;
         sec = arr[i];
      } else if (arr[i] < third)
      third = arr[i];
   }
   cout << "First min = " << first << endl;
   cout << "Second min = " << sec << endl;
   cout << "Third min = " << third << endl;
}
int main() {
   int array[] = {4, 9, 18, 32, 12};
   int n = sizeof(array) / sizeof(array[0]);
   getThreeMins(array, n);
}

Output

First min = 4
Second min = 9
Third min = 12
raja
Published on 18-Dec-2019 11:24:33
Advertisements