- 0
Notifications Mark All Read
- Login
- Get Prime
C++ Program to find the second smallest element in an array
Second smallest element in an array
An array is a group of similar type of data that are addressed by an common name (Arr[]). Array of any type can be created and may have one or more dimensions, i.e. 1-D Array, 2-D Array etc. Here we will learn how to code a C++ program for finding second smallest element in an array.
Algorithm :
- Take the size of the array from the user and store it in variable say n.
- Declare an array of n size and take n input elements for the array from the user.
- Now , Declare two variable say min1 and min2.
- Initialize them min1 as INT_MAX and min2 as INT_MAX-1
- Iterate from i=0 to i=n-1 and check if the min1 >a[i] then update min2=min1 and min1 = a[i].
- Else If min2 > a[i], then update min2 as min2 = a[i].
C++ code based on above algorithm
#include <iostream>
using namespace std;
int main(){
int n;
cin>>n;
int a[n];
for ( int i = 0 ; i < n; i++)
cin>>a[i];
int min1 = INT_MAX, min2 = INT_MAX-1;
for (int i = 0; i < n; i++) {
if (a[i] < min1) {
min2 = min1;
min1 = a[i];
}
else if (a[i] < min2) {
min2 = a[i];
}
}
cout<<max2;
}
Input :
5
7 8 1 9 2
Output :
2
Login/Signup to comment
#include
using namespace std;
int main(){
int n;
cin>>n;
int a[n];
for(int i=0;i>a[i];
}
for(int i=0;i<n-1;i++){
for(int j=i+1;ja[j]){
int temp=a[j];
a[j]=a[i];
a[i]=temp;
}
}
}
for(int i=0;i<n;i++){
if(i==1){
cout<<a[i]<<" ";
break;
}
}
return 0;
}