Find the second smallest element in array C Program
Simple C program to find second smallest element in unsorted array. C program to find second minimum element in unsorted array.
Our task is to find second smallest element in array. To find this we use two variable min and second_min. First we initialize min and second_min to largest value of integer in C language. For this we use c library limits.h in which largest value of integer is INT_MAX.
Now compare min and second_min with the element with the array elements. If we find any element less than min then update second min to min and min to array element. Now for example array is { 12,24,65,32,89,43,18,62};.
See the explanation:
Our task is to find second smallest element in array. To find this we use two variable min and second_min. First we initialize min and second_min to largest value of integer in C language. For this we use c library limits.h in which largest value of integer is INT_MAX.
Now compare min and second_min with the element with the array elements. If we find any element less than min then update second min to min and min to array element. Now for example array is { 12,24,65,32,89,43,18,62};.
See the explanation:
min=INT_MAX; second_min=INT_MAX;
arr[0] = 12 and 12 < min
so second_min=min; min=arr[0];
arr[1] = 24; 24 > min;
but 24 < second_min;
second_min = 24;
arr[2] = 65
65 !< min and 65 !<second_min
so min=12 and second_min=24;
and so on...
arr[0] = 12 and 12 < min
so second_min=min; min=arr[0];
arr[1] = 24; 24 > min;
but 24 < second_min;
second_min = 24;
arr[2] = 65
65 !< min and 65 !<second_min
so min=12 and second_min=24;
and so on...
/* C Program to find second minimum element in array */ #include<stdio.h> #include<limits.h> int SecondMin(int arr[],int size) { int i,second_min=INT_MAX,min=INT_MAX; for(i=0;i<size;i++) { if(arr[i]<min) { second_min=min; min=arr[i]; } else if(arr[i]<second_min&&arr[i]!=min) { second_min=arr[i]; } } return second_min; } int main() { int arr[]={12,24,65,32,89,43,18,62}; int n=sizeof(arr)/sizeof(arr[0]); int second_min=SecondMin(arr,n); printf("Second minimum = %d",second_min); return 0; }