Java Program to find the second smallest element of an array .
Objective
Write a Java program to find the second smallest element of an array.
Algorithm / Approach
- Take the array elements as input from the user.
- First Pass: Loop through the array to find the smallest element (
min) and remember its index (m). - Initialize a candidate for the second smallest element (
smin) using an element from the opposite end of the array (e.g.,a[n-m-1]). - Second Pass: Loop through the array again. If the current element is smaller than
sminAND its index is notm(the smallest element's index), updatesmin. - Print
smin.
Test.java
import java.util.Scanner;
class Test {
void min() {
Scanner s=new Scanner(System.in);
System.out.print("Enter Size: ");
int n = s.nextInt();
int a[]=new int[n];
System.out.print("Enter Element: ");
for(int i=0; i< n; i++){
a[i]= s.nextInt();
}
int min = a[0], m = 0;
for(int i =1; i< n; i++) {
if(a[i] < min) {
min = a[i];
m = i;
}
}
int smin = a[n-m-1];
for(int i =0 ; i< n; i++) {
if(smin> a[i] && m!= i) {
smin = a[i];
}
}
System.out.print("2nd Min = "+smin);
}
public static void main(String[] a)
{
Test t = new Test();
t.min();
}
}
Expected Output
Enter Size: 5 Enter Element: 5 7 9 6 8 2nd Min = 6
Explanation of the Program
- Finding the second smallest element requires ignoring the absolute minimum. This program accomplishes it in two independent passes.
- In the first pass, it locates the smallest element and specifically records its index.
- In the second pass, it searches for a new minimum but explicitly adds the condition
m != ito ensure the absolute minimum is excluded from consideration. - Note: A more optimized version can achieve this in a single pass by tracking both minimums simultaneously.
Complexity
Time Complexity
O(n)
Space Complexity
O(n)