Find second smallest element of array
Algorithm:
1. Initialize both first and second smallest as INT_MAX.
2. Traverse elements of array
i. If the element of array is smaller than first , then update second with first and first with that element.
ii. If the element of array is smaller than second , then update second with that element and check if that element of array is not equal to first element.
Implementation in C:
#include<stdio.h>
#include<limits.h>
void printsmall(int,int);
int main()
{
int arr[]={19,18,17,38,12,15,9,6,4};
printsmall(arr,9);
return 0;
}
void printsmall(int arr[], int n)
{
int i,first,second;
first=second=INT_MAX;
for(i=0;i<n;i++)
{
if(arr[i]<first)
{
second=first;
first=arr[i];
}
else if(arr[i]<second && arr[i]!=first)
{
second=arr[i];
}
}
if(second==INT_MAX)
{
printf("No second smallest element");
}
if(first<second)
{
printf("Smallest element in array is: %d and second smallest element is: %d",first,second);
}
}
Time Complexity: O(n) in Worst Case
1. Initialize both first and second smallest as INT_MAX.
2. Traverse elements of array
i. If the element of array is smaller than first , then update second with first and first with that element.
ii. If the element of array is smaller than second , then update second with that element and check if that element of array is not equal to first element.
Implementation in C:
#include<stdio.h>
#include<limits.h>
void printsmall(int,int);
int main()
{
int arr[]={19,18,17,38,12,15,9,6,4};
printsmall(arr,9);
return 0;
}
void printsmall(int arr[], int n)
{
int i,first,second;
first=second=INT_MAX;
for(i=0;i<n;i++)
{
if(arr[i]<first)
{
second=first;
first=arr[i];
}
else if(arr[i]<second && arr[i]!=first)
{
second=arr[i];
}
}
if(second==INT_MAX)
{
printf("No second smallest element");
}
if(first<second)
{
printf("Smallest element in array is: %d and second smallest element is: %d",first,second);
}
}
Time Complexity: O(n) in Worst Case
Comments
Post a Comment