ADVERTISEMENT
ADVERTISEMENT

Java program to find second smallest element in an array

In this java program, we are reading an integer array of N elements and finding second smallest element among them.
Submitted by Chandra Shekhar, on February 03, 2018

Given an array of N integers and we have to find its second minimum/smallest element using Java program.

Example:

    Input:
    Enter number of elements: 4
    Input elements: 45, 25, 69, 40

    Output:
    Second smallest element in: 40

Program to find second smallest element from an array in java

import java.util.Scanner;

public class ExArrayFindSecondSmallest {
  public static void main(String[] args) {
    // Intialising the variables
    int n, min;
    Scanner Sc = new Scanner(System.in);

    // Enter the number of elements.
    System.out.print("Enter number of elements : ");
    n = Sc.nextInt();

    // creating an array.
    int a[] = new int[n];

    // enter array elements.
    System.out.println("Enter the elements in array : ");
    for (int i = 0; i < n; i++) {
      a[i] = Sc.nextInt();
    }

    for (int i = 0; i < n; i++) {
      for (int j = i + 1; j < n; j++) {
        if (a[i] > a[j]) {
          min = a[i];
          a[i] = a[j];
          a[j] = min;
        }
      }
    }
    System.out.println("The Smallest element in the array is :" + a[1]);
  }
}

Output

Enter number of elements : 4
Enter the elements in array : 
45
25
69
40
The Smallest element in the array is :40

Java Array Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.