Explore

Edit

Edit

# Program to find the second smallest element in an array | FACE Prep

Published on 09 Mar 2020

Finding the second smallest element in an array can be done in 3 different ways

They are:

• Method 1: By sorting the array in ascending order and then displaying the second element.
• Method 2: By traversing the array twice. In the first traversal find the smallest element (x) and in the second traversal, skip x and find the next smallest element which is >x.
• Method 3: By traversing the array and storing the smallest element as and when we encounter it.

## Method 1 to find the second smallest element in an array

An easier approach to finding the second smallest element in an array will be sorting the array completely and then returning the second element in the array.

Algorithm

• Declare an array and input the array elements.
• Sort the array (sort(arr, arr+n)).
• Display the second element from the array.

C
C++

Output
Input - Enter the number of elements : 3 Input the array elements: 2 3 4 Output - The second smallest element is 3

## Method 2 to find the second smallest element in an array

The second smallest element can be also found by traversing the array two times. In the first traversal, the smallest element (first_smallest) in the array is found and in the second traversal, the smallest element other than the first_smallest element is found.

Algorithm

• Declare an array and input the array elements.
• Find the smallest element (first_smallest) in the array in the first traversal.
• Find the smallest element (second_smallest) by skipping the first_smallest element.
• Display second_smallest.

C
C++

Output
Input- Enter the number of elements : 3 Input the array elements: 5 10 15 Output- The second smallest element is 10

## Method 3 to find the second smallest element in an array

The most efficient method will be finding the second smallest element by traversing the array once.

Algorithm

• Declare an array and input the array elements.
• Initialize first_smallest = second_smallest = INT MAX;
• Start traversing the array and assign the smallest element to first_smallest.
• In the same traversal, if the next element is smaller than first_smallest, make that as first_smallest and make first_smallest as second_smallest.
• Display second_smallest.

C
C++

Output
Input- Enter the number of elements : 3 Input the array elements: 5 10 15 Output- The second smallest element is 10

Recommended Programs