C Program to find second smallest element of an array.
Objective
Write a C program to find the second smallest element of an array.
Algorithm / Approach
- Read an array of size
n. - Find the absolute smallest element (
min) and save its exact index position inj. - Initialize the second smallest
sminto a different element (e.g., the last element). - Loop through the array again to find the minimum value, BUT ignore the element at index
j(if smin > a[i] && j != i). - Print
smin.
main.c
#include<stdio.h>
int main() {
int a[50],n,i,j=0,min,smin;
printf("Enter Array Size: ");
scanf("%d",&n);
printf("Enter %d element: ",n);
for(i=0;i< n;i++)
scanf("%d",&a[i]);
min=a[0];
for(i=1;i< n;i++){
if(min > a[i]) {
min = a[i];
j = i;
}
}
smin=a[n-j-1];
for(i=1;i< n;i++){
if(smin > a[i] && j != i)
smin =a[i];
}
printf("2nd smallest:%d",smin);
return 0;
}
Expected Output
Enter Array Size: 5 Enter 5 element: 1 2 3 4 5 2nd smallest:2
Explanation of the Program
- To find the second smallest, we must first identify the absolute smallest and "remove" it from consideration.
- Instead of physically deleting the smallest element (which is expensive in an array), we just record its index (
j). When we do our second pass to find the smallest number, we explicitly tell theifstatement to ignore indexj.
Complexity
Time Complexity
O(n) - Two separate passes through the array.
Space Complexity
O(n)