×

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 throw

Java throw Sometimes it is required in the code to throw an exception deliberately. In order to achieve the same, the Java throw keyword should be used. One can throw either...

3 minutes read.

Java Thread Lifecycle: States and Stages

Multithreading Multithreading is one of the most important features in object-oriented programming, and this multithreading can be implemented by various object-oriented programming languages like Java, Python, and C++. A multithreaded process...

7 minutes read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.

How to Split the String in Java with Delimiter

In Java, splitting strings is a significant and typically used activity while coding. Java gives different ways of dividing the String. The most widely recognized way is to use the...

3 minutes read.

How to Convert int to long in Java

How to Convert int to long in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

Java Session

Session indicates interval of time. A session is a simple  time interval in which servers and client interacts. To maintain the state of the client or user we use technologies...

5 minutes read.

Camel Case in Java

Java names its classes, interfaces, methods, as well as variables using camel-case syntax. If the name consists of two words, the second word will always begin with a capital letter,...

3 minutes read.

Java Interface Lock

A synchronisation method called the Lock interface is available as of JDK 1.5. It is comparable to a synchronised block but more complex and versatile. The package java.util.concurrent contains the...

4 minutes read.

Java program to find frequency of characters in a string

In this article, you will understand the how to find the frequency of characters in strings by using Java programming language. Along with this, you will understand the hashing concept...

3 minutes read.

Tug of War in Java

As in the tug-of-war issue, we must divide the given collection of n numbers into two groups of sizes that are equal or nearly equivalent. A minimum difference must exist...

5 minutes read.

How to calculate time difference in Java

In this tutorial, we learned about how to calculate time differences in java language and which methods use to find the difference and its example. Prerequisite To understand this example, you need...

5 minutes read.

Determine the Upper Bound of a Two-Dimensional Array in Java

Multi-Dimensional Array Multi-faceted exhibits in Java are regular and can be named various clusters. Information in a two-layered bunch in Java is put away in 2D even structure. A two-layered collection...

3 minutes read.

What is interpreter in Java?

The programming language Java is platform-neutral. Therefore, can use Java on any platform that supports the Java processor. The Piece of software transforms the Java bytecode contained in the class...

5 minutes read.

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

Java Macros

Macros are additions to the JDK 7 compiler in Java. Compile time macros are added and supported. Macros are Java classes that are instantiated and executed during the compilation process....

2 minutes read.

Java program to print matrix in Z form

In this article, you will be acknowledged about what is a matrix along with an example. Also, most importantly, you will learn how to print matrix in Z form. What is...

5 minutes read.

Java Integer toUnsignedString() method

The toUnsignedString() method of Java Integer class returns a string representation of the argument as an unsigned decimal value. The second syntax returns a string representation of the given argument as...

2 minutes read.

Java Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.