# Find Second Smallest Number in an Array : Java Code

Write a java program to find second smallest number in an array. Given an input array, write a java code to print second smallest number of an array.

For example :

arr = {-1, 7, 1, 34, 18}

The second smallest number in this array is 1.

In this tutorial, I have explained how we can find second smallest number in an array by sorting and without sorting an array.

METHOD 1: Find second smallest number by sorting an array

The easiest approach is to sort the array.  After sorting an array the element present at 1 index is the second smallest number of an array.

Bubble Sort Program in Java

Insertion Sort Program in Java

For sorting either we can write our own sort method using Sorting algorithms or we can use java inbuilt sort method. The time complexity of sorting an array is O(nlogn).

NOTE: If the element of an array is repeated then this approach won’t work.

To understand this let’s take an example.

int num[] = {1, 9, 5, 1, 8, -1, 3, -1};

So what will be the second smallest number if we can use above method (sort and pick the element at 1 indext). The element is -1 which is wrong.

The best approach is to traverse an array to find second smallest number. Let’s implement this approach.

Subscribe Our Tutorials

Find Second Smallest Number of an Array

## Find Second Smallest Number in an Array: Java Code

In this programming example, I have explained how we can find second smallest number without sorting an array. To find second smallest number, i have traversed an array and maintained two flags smallest and secondSmallest.

The time complexity of this approach is O(n).

Java Program to Find Second Largest Number in an Array

In this video tutorial, I have explained multiple approaches to find second smallest number in an array.