Adsense 728 * 15

Search

Custom Search

Write a Program to Find Second Smallest Number in an Unsorted Array

Logic To Find Second Smallest Element

1. Take two variables smallest and secondsmallest and assign it to INT_MAX (maximum value for this use limits.h header).

2. Run a loop,

     a) If value is smaller than smallest, then update smallest and secondsmallest.
     b) Else if the current element is smaller than second then update  secondsmallest.

Program to Find Smallest Element Without Using Comparison Operator

Program to Find Smallest Element in An Array

Program to Find Second Smallest Number in an Unsorted Array 

 



#include <stdio.h>
// Header for INT_MAX
#include <limits.h>

main()
{
   
   int arr[] = {1,4,2,5,5};
   
   int smallest=INT_MAX,i;
   int secondsmallest = INT_MAX;
   
   int n = sizeof(arr)/sizeof(arr[0]);
   
   for(i=0;i<n;i++){
       
       if(arr[i]<smallest){
           secondsmallest = smallest;
           smallest = arr[i];
       }else if(arr[i]<secondsmallest && arr[i] !=smallest){
		  secondsmallest = arr[i];
	}
   }

	 printf("Second smallest number is %d",secondsmallest);
   
} 

No comments:

Post a Comment