Find the smallest and second smallest elements in an array in C++


Suppose we have an array of n elements. We have to find the first, second smallest elements in the array. First smallest is the minimum of the array, second smallest is minimum but larger than the first smallest number.

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

Example

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

Output

First smallest = 4
Second smallest = 9

Updated on: 04-Nov-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements