×

Second Smallest Number in an Array in Java

By sorting the arrays and returning the second element, we can use Java to discover the second-smallest number in the array.

Input:  arr[] = {10, 11, 13, 15, 34, 51}
Output: The smallest element is 10 and 
        The second smallest element is 11

Method 1: By sorting the array using the sort function

SecondSmallest1.java

// Public class declaration
import java.io.*;
import java.util.*;
public class SecondSmallest1 
{  
// public static method is used 
// static methods can be implemented without the creation of Objects
public static int secondSmallest(int [ ]  arr ,int n ) {  
// Sorting the algorithm using the sort function
Arrays.sort(arr);
System.out.println( ) ;
System.out.println("After sorting the elements are");
for(int i = 0 ; i < n ; i++ )
{
    System.out.print(arr[ i ] + " ") ; 
}
System.out.println( );
//2nd smallest element is present at index 1 because the index starts from 0 
// returning the seconds element
return arr[1] ;  
}  
// Main section of the program where execution starts
public static void main (String s[ ])
{  
//  input array declaration and initialization in a static way
int inputarray1[ ] = { 11,12,25,36,63, 52 };  
int inputarray2[ ] = { 424  166  9, 177  233,212  515 } ;  
// storing the length of the array into integer variable n1
int n1 = inputarray1.length ;
// storing the length of the array into integer variable n2
int n2 = inputarray2.length ;
System.out.println (" First array elements before sorting are " ) ;
// printing the total array 
for(int i = 0 ; i < n1 ; i++ )
{
// printing each element
    System.out.print(inputarray1[ i ] + " " ) ;   
}
System.out.println( " Second smallest element is : "+ secondSmallest ( inputarray1 , n1 ) ) ;  
System.out.println( " Second  array elements before sorting are " ) ;
// printing the array elements
for(int i = 0 ; i < n1 ; i++ )
{
// printing each element of the array
    System.out.print ( inputarray2[ i ] + " " ) ; 
}
System.out.println ( ) ;
System.out.println (" Second smallest element is  "+ secondSmallest( inputarray2 , n2 ) ) ;  
}}  

Output

The first array elements before sorting are 
11 12 25 36 63 52 
After sorting, the elements are
11 12 25 36 52 63 
 The second smallest element is  12
 The second array of elements before sorting is 
424 166 9 177 233 212 
After sorting, the elements are
9 166 177 212 233 424 515 
 The second smallest element is: 166

Method 2: By sorting the array without using the sort built-in function

SecondSmallest2.java

// Public class declaration 
public class SecondSmallest2
{  
// public static method is used 
// static methods can be implemented without the creation of Objects
public static int secondSmallest (int [ ], int n ) {  
// declaring a temporary variable
int t ;  
// Iterating through the array using for loop from the first index
// Sorting the algorithm
for (int j = 0;j < n;j++)   
        {  
            // Iterating through the array using for loop from j+1 index
            for (int i = j + 1;i < n;i++)   
            {  
                // swapping the elements if the first element is greater than the second element
                if ( a[j] > a [i])   
                {  
// storing value in a temporary variable and swapping the values
                    t = a[j] ;  
                    a [j] = a [i] ;  
                    a [i] = t ;  
                }  
            }  
        }  
        //2nd smallest  element is present at index 1 because the index starts from 0 
       return a [1] ;  
}  
// Main section of the program where execution starts
public static void main (String s [ ])
{  
// array initialization and declaration
// taking input arrays in a static way
int inputarray1 [ ] = { 11, 12, 25, 36, 63, 52 } ;  
int inputarray2 [ ] = { 424, 166, 9, 177, 233,212, 515 } ; 
// finding the length of the array using the length function for arrays
// storing the length of the array into integer variable n1
int n1 = inputarray1.length ;
// storing the length of the array into integer variable n2
int n2 = inputarray2.length ;
System. out.println(" First array elements are " ) ;
for(int i = 0 ; i < n1 ; i++ )
{
// printing each element of the array
    System.out.print( inputarray1 [ i ] + " " ) ; 
}
System.out.println( ) ;
// printing the second smallest number
System.out.println( " Second smallest element is : "+ secondSmallest ( inputarray1 , n1 ) ) ;  
// printing the second array of elements
System.out.println ( " Second  array elements are " ) ;
for(int i = 0 ; i < n1 ; i++ )
{
// printing each element of the array
    System.out.print ( inputarray2[ i ] + " " ) ; 
}
System.out.println( ) ;
// printing the second smallest element in the  given array
System.out.println (" Second smallest element is : "+ secondSmallest ( inputarray2 , n2  ) ) ;  
}
}  

Output

The first array elements are 
11 12 25 36 63 52 
 The second smallest element is : 12
 The second array of elements are 
424 166 9 177 233 212 
 The second smallest element is : 166

Method 3: Using Collections

SecondSmallest3.java

// scanner class importing packages
import java.util.*;  
public class SecondSmallest3
{  
    // static method declaration, which is used to find the second smallest element in the array
public static int secondSmallest(Integer [] arr, int sum )
{  
    // converting the provided Integer array into the list by using Array.asList() method
List<Integer> l = Arrays.asList (arr);  
// Sorting the collection framework using the Collections. sort() method
Collections.sort(l);  
// storing the second value into the variable r
int r = l.get(1);  
// returning the result
return r ;  
}  
// main method of the section from where execution begins
public static void main(String s [] ){  
// creating an object for the scanner class to take inputs from the user during run time
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of the first array ");
// enter the array size of the first array
// storing the size into n1 integer variable
int n1 = sc.nextInt ();
// creating an integer array variable for storing the elements in an array
Integer a[] = new Integer[n1];
System.out.println("Enter the first array elements");
// enter the first array of elements
// using for loop to store the array elements into array
for (int i=0;i<n1;i++)
{
    a[i] = sc.nextInt ();
}
System.out.println();
System.out.println("Enter size of the second array ");
// enter the size of the second array
// storing the size into integer variable n2
int n2 = sc.nextInt ();
// creating an integer array variable for storing the elements in an array
Integer b[] = new Integer[n2];
System.out.println("Enter the second array elements");
// enter the second array of elements
for (int i=0;i<n2;i++)
{
    b[i] = sc.nextInt ();
} 
// calling the function and printing it
System.out.println(" Second Smallest element in the first array is "+secondSmallest(a,n1));  
System.out.println();
// calling the function and printing it
System.out.println("Second Smallest element in the second array is "+secondSmallest(b,n2));  
}}  

Output

Enter the size of the first array 
5
Enter the first array of elements
12 43 12 1 10
Enter the size of the second array 
5
Enter the second array of elements
12 23 21 45 33
 The second Smallest element in the first array is 10
The second Smallest element in the second array is 21

Method 4: Using two variables

1) Set the first and second smallest values to be equal to INT MAX

2) Repeat step two for each component.

a) Update the first and second elements if the current element is smaller than the first.

b) Or else, update second if the current element is smaller than it.

SecondSmallest4.java

// importing the packages 
import java.io.*;
import java.util.*;


class SecondSmallest4
{
/* static method declaration */ 
/* static method can be used without creating the objects for the class */
static void secondSmallest(int a[])
{
    /* declaring and initializing two integer variables */ 
int f1;
int ans;
int n=a.length;
/* if the size of the array is less than 2, then there will be no second term in the array */
/* so it should print invalid input */
if (n < 2) // checking the size of the array
{
    /* printing the invalid input */
System.out.println(" Invalid Input ");
// return statement
return;
}
        //initializing the two variables 
f1 =  Integer.MAX_VALUE;
ans =  Integer.MAX_VALUE;
for (int j = 0; j < n ; j ++)
{
if (a[j] < f1)
{
ans = f1;
f1 = a[j];
}
else if (a[j] < ans && a[j] != f1 )
ans = a[j];
}
if (ans == Integer.MAX_VALUE)
System.out.println(" No second smallest element int he given array ");
else
System.out.println("The  second Smallest element is " + ans );
}
// Main section of the program, from execution, begins
public static void main (String[] args)
{
    Scanner sc=new Scanner(System.in);


    System.out.println(" Enter the size of the array");
    // variable declaration and initializing it to store the array size 
    int n1= sc.nextInt();
    // array declaration
    int a[]=new int[n1];
    System.out.println("Enter the array elements ");
    // enter the array elements
for(int j=0;j<n1;j++)
{
    a[j]=sc.nextInt();
}
// calling the secondSmallest method
secondSmallest(a);
}
}

Output

Enter the size of the array
5
Enter the array of elements 
12 34 22 66 45
The  second smallest element is 22

Related Topics

Java File Extension

A computer file's suffix is called its file extension. It is easily recognized since it appears immediately after a period (.) in the file name. Consider the file Demo.java as an...

3 minutes read.

Differences between Lock and Monitor in Java Concurrency

In this tutorial, we will discuss the overview of Lock and Monitor and the differences between them. Introduction Java Concurrency is the ability to perform specific tasks at a time parallelly. The...

4 minutes read.

Coin change problem in dynamic programming

In this tutorial, we will understand a popular problem called the coin changeproblem through dynamic programming. This problem checks the logical and critical thinking ability of the person. Dynamic Programming...

5 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

Java Switch Keyword

In this article we are going to learn the concept of a java switch keyword. Generally, java case keyword is used with the switch statements or keyword.Switch keyword is implemented in...

3 minutes read.

Java Math asin() Method

The asin() method of Math class computes the trigonometric Arc Sine (inverse of sine ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double asin(double a) Parameters: The...

1 minute read.

Java Math nextDown() Method

The nextDown() method of Math class returns the floating-point number adjacent to the argument in direction of the negative infinity. Syntax: public static double nextDown (double d)public static float nextDown (float f) Parameters: The...

2 minutes read.

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the...

5 minutes read.

Session Tracking in Java

When a series of requests from the same User (i.e., requests coming from the same browser) occurs over an extended period of time, servlets employ a mechanism known as session...

3 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

Synchronized Keyword in Java

Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from...

6 minutes read.

Static and Dynamic Binding in Java

Data Binding in Java The relation between a class and method or class and field is known as Data Binding. In Java, we can create a class for Student_info, but until we...

2 minutes read.

Java Math tanh() Method

The tanh() method of Java Math class returns the hyperbolic tangent of the specified double value. Syntax: public static double tanh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic tangent is to...

2 minutes read.

How to add Elements in Array in Java

Consider an array of the size n, in the given size we must add the elements in the given array. In this tutorial we are preferred to learn how to add...

3 minutes read.

Java Constant

A constant is an unchangeable entity in coding, as its title implies. The value which cannot be altered, in other terms. We shall understand about Java constants and exactly how...

3 minutes read.

Accessors and Mutator in Java

Introduction Accessors and mutators are used in Java to get and set the value of private fields, respectively. Accessors and mutators are both referred to as getters and setters, respectively. The...

6 minutes read.

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.

Dictionary in Java

Dictionary in Java The Dictionary class represents a key-value relation which maps keys to values. In Dictionary class, every key and every value is an object. It is an abstract class associated with...

2 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

Java Lambda foreach

Before understanding lamda foreach, one must know about foreach loop in Java. foreach loop in Java Since J2SE 5.0, there has been a for-each loop in Java, also known as an extended...

4 minutes read.