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
using namespace std;
int getTwoSmallest(int arr[], int n) {
   int first = INT_MAX, sec = INT_MAX;
   for (int i = 0; i 

Output

First smallest = 4
Second smallest = 9
Updated on: 2019-11-04T10:03:23+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements