WAP to find the second smallest number of an array
Objective
Write a C++ program to find the second smallest element of an array.
Algorithm / Approach
- Find the absolute smallest element (
min) and save its exact index position inm. - Initialize the second smallest
sminto an element at the opposite end of the array. - Loop through the array again to find the minimum value, BUT completely ignore the element at index
m(if smin > a[i] && m != i). - Print
smin.
main.cpp
#include<iostream>
using namespace std;
int main() {
int m = 0, a[5],min,smin ;
cout<<"Enter 5 Elements : ";
for(int i =0; i< 5; i++) {
cin>>a[i];
}
min = a[0];
for(int i =1; i< 5; i++) {
if(a[i] < min) {
min = a[i];
m = i;
}
}
smin = a[5-m-1];
for(int i =0 ; i< 5; i++) {
if(smin> a[i] && m!= i) {
smin = a[i];
}
}
cout<<"Second Min = "<< smin;
return 0;
}
Expected Output
Enter 5 Elements : 1 3 45 32 54 Second Min = 3
Explanation of the Program
- To find the second smallest, we first find the absolute smallest and record its index.
- During our second pass through the array, we explicitly tell our
ifstatement to skip that specific index. This forces the algorithm to find the smallest of the *remaining* numbers.
Complexity
Time Complexity
O(n) - Two separate O(n) passes.
Space Complexity
O(n)