Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to find the second smallest element of an array .

Java Code Example — Array Programs

ADVERTISEMENT

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

  1. Take the array elements as input from the user.
  2. First Pass: Loop through the array to find the smallest element (min) and remember its index (m).
  3. 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]).
  4. Second Pass: Loop through the array again. If the current element is smaller than smin AND its index is not m (the smallest element's index), update smin.
  5. 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 != i to 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)
ADVERTISEMENT