Java Program to Find the Smallest Number in an Array

In this blog, we’ll explore different methods to accomplish this task, ranging from simple sorting techniques to utilizing Java’s built-in utility classes.

When working with arrays in Java, one common task is to find the smallest number within an array. Whether you’re dealing with data analysis, algorithms, or any application that requires data manipulation, knowing how to efficiently find the smallest element is crucial. 

What is the smallest number in an array?

The smallest number in an array is the numeric value that is lower than or equal to all the other numbers present in the array. In other words, it’s the minimum value among the elements contained within the array. When dealing with a collection of numbers, finding the smallest number can be important for various purposes, such as optimization problems, data analysis, sorting algorithms, and more.

Example of Smallest number in an array 

For example, in the array `[5, 2, 9, 1, 7]`, the smallest number is `1`, as it is the lowest value among all the elements in the array.

Methods to find the smallest number in an array

  1. By sorting the array and returning the 1st element
  2. Using Array
  3. Using Collections

Find the Smallest Number by sorting the array and returning the 1st element

The below Java program aims to find the smallest number within an array using a simple sorting approach known as “selection sort.” 

// Java Program to Find the Smallest Number in an Array
public class SmallArrayEx{  
    public static int getSmallest(int[] a, int total){  
        int temp;  
        for (int i = 0; i < total; i++)   
        {  
            for (int j = i + 1; j < total; j++)   
            {  
                if (a[i] > a[j])   
                {  
                    temp = a[i];  
                    a[i] = a[j];  
                    a[j] = temp;  
                }  
            }  
        }  
       return a[0];  
    }  
    public static void main(String args[]){  
        int a[]={100,24,56,36,83,29};   
        System.out.println("Smallest: "+getSmallest(a,6));  
    }
}

Explanation of the code:

The program starts by defining a class named `SmallArrayEx`. Inside this class, a static method named `getSmallest` is implemented, which takes two arguments: an array `a` and the total number of elements in the array (`total`).

The method employs a nested loop structure for iterating through the array. The outer loop traverses each element, while the inner loop compares the current element with subsequent elements. If an element smaller than the current one is found, a swapping mechanism is executed using a temporary variable `temp`. This sorting process ensures that the smallest element gradually moves towards the front of the array.

Finally, the method returns the first element of the sorted array, which is now the smallest number. In the `main` method, an array `a` is initialized with numeric values, and the `getSmallest` method is called with the array and its size. The program then prints the smallest number obtained using this sorting technique.

It’s worth noting that while this approach works, it’s not the most efficient sorting method for larger arrays due to its time complexity of O(n^2). More advanced sorting algorithms like quicksort or mergesort offer better performance for larger datasets.

Output:

Smallest: 24

Get complete Java Programming Exercises and Solutions here!

Find the Smallest Number by using Arrays

The provided Java program is designed to find the smallest number within an array using the built-in sorting capability of the `Arrays` class.

// Java Program to Find the Smallest Number in an Array
import java.util.*;  
public class SmallArrayExa{  
    public static int getSmallest(int[] a, int total){  
        Arrays.sort(a);  
        return a[0];  
    }  
    public static void main(String args[]){  
        int a[]={44,64,93,72,33,27,55};  
        System.out.println("Smallest: "+getSmallest(a,7));  
    }
}

Explanation of Code:
The program begins by importing the `java.util.*` package, which includes the necessary classes for array manipulation.

Within the `SmallArrayExa` class, a static method named `getSmallest` is implemented. This method takes two arguments: an integer array `a` and the total number of elements in the array (`total`). The core functionality of the method lies in the single line `Arrays.sort(a);`, which sorts the array in ascending order.

After sorting, consequently, the smallest number is located at the beginning of the array (`a[0]`). As a result the method directly returns this smallest value.

In the `main` method, an array `a` is initialized with a series of numeric values. The `getSmallest` method is then invoked with the array and its size, and the smallest number is obtained through the sorting process. The program concludes by printing the smallest number found using the provided array and the `getSmallest` method.

Utilizing the `Arrays.sort()` method simplifies the process of finding the smallest number, but it’s important to acknowledge that sorting itself carries a time complexity of O(n log n). For larger arrays, alternative approaches like iterating through the array could offer more efficient solutions.

Output:

Smallest: 27

Find the Smallest Number using Collections

The provided Java program is designed to find the smallest number within an array using Java’s built-in utility classes, such as `Arrays` and `Collections`.

// Java Program to Find the Smallest Number in an Array
import java.util.*;  
public class SmallArrayEx{  
    public static int getSmallest(Integer[] abc, int total){  
        List<Integer> list=Arrays.asList(abc);  
        Collections.sort(list);  
        int element=list.get(0);  
        return element;  
    }  
    public static void main(String args[]){  
        Integer abc[]={56,212,556,64,31,275};  
        System.out.println("Smallest: "+getSmallest(abc,6));  
    }
} 

Explanation of Code:
The program begins by importing the necessary utilities.

Inside the `SmallArrayEx` class, a static method named `getSmallest` is implemented. This method takes two arguments: such as an array of `Integer` values named `abc` and the total number of elements in the array (`total`).

Within the method, the `Arrays.asList()` function converts the `abc` array into a `List<Integer>`. Then, the `Collections.sort()` method is used to sort the list in ascending order. After sorting, the smallest element is obtained by retrieving the element at index 0 using `list.get(0)`.

In the `main` method, an array `abc` is initialized with `Integer` values. The `getSmallest` method is called with the array and its size as arguments. Finally, the program prints the smallest number found using this approach.

This method of finding the smallest number using built-in utilities leverages Java’s convenient features and offers an efficient solution, particularly for larger datasets.

Output:

Smallest: 31

Various Java Programs to Find 2nd Smallest Number in an Array

  1. By sorting the array
  2. Using Array
  3. Using Collections

Find the 2nd Smallest Number in an array by sorting the array

The provided Java program aims to find the second smallest number within an array using the “selection sort” technique.

// Java Program to Find 2nd Smallest Number in an Array
public class SmallArrayEx
{  
    public static int getSecondSmallest(int[] a, int total){  
        int temp;  
        for (int i = 0; i < total; i++)   
        {  
            for (int j = i + 1; j < total; j++)   
            {  
                if (a[i] > a[j])   
                {  
                    temp = a[i];  
                    a[i] = a[j];  
                    a[j] = temp;  
                }  
            }  
        }  
       return a[1];//2nd element because index starts from 0  
       }  
       public static void main(String args[]){  
           int a[]={16,24,58,64,39,2}; 
           System.out.println("Second smallest: "+getSecondSmallest(a,6));  
       }
}

Check out  Java Interview Questions and Answers, Now!

Explanation of code:
The program defines a class named `SmallArrayEx`. Within this class, a static method named `getSecondSmallest` is implemented, which takes an array `a` and the total number of elements in the array (`total`) as arguments.

The method utilizes a nested loop structure to traverse through the array. Firstly, the outer loop selects each element, and subsequently, the inner loop compares it with subsequent elements. If a smaller element is encountered, a swapping mechanism is executed using a temporary variable `temp`. This sorting process progressively moves the smallest elements towards the beginning of the array.

Finally, the method returns the element at index 1 of the sorted array, representing the second smallest number. The ‘main’ method initializes an array ‘a’ with integer values. The `getSecondSmallest` method is called with the array and its size, and the program then prints the second smallest number achieved through this sorting approach.

It’s important to note that this method’s efficiency is limited for larger arrays due to its time complexity of O(n^2). Quicksort or mergesort, more advanced sorting algorithms, better suit larger datasets.

Output:

Second smallest: 16

Using Arrays

This Java program focuses on identifying the second smallest number within an array using the built-in ‘Arrays’ class for sorting.

// Java Program to Find 2nd Smallest Number in an Array
import java.util.*;  
public class SmallArrayEx{  
    public static int getSecondSmallest(int[] a, int total)
    {  
        Arrays.sort(a);  
        return a[1];  
    }  
    public static void main(String args[]){  
        int a[]={14,26,53,69,31,28};   
        System.out.println("Second Smallest: "+getSecondSmallest(a,6));  
    }
}  

Explanation of code:
After importing the required `java.util` package, the program defines the `SmallArrayEx` class.

Within this class, there’s a static method named `getSecondSmallest`, which takes two arguments: an integer array `a` and the total number of elements in the array (`total`).

The method sorts the array `a` in ascending order using `Arrays.sort(a)`. Consequently, the second smallest element is then accessed using `a[1]`, considering array indices start from 0.

The ‘main’ method initializes an array ‘a’ with integer values. By invoking the `getSecondSmallest` method with the array and its size as arguments, the program retrieves the second smallest number. This value is then printed using the `System.out.println` statement.

The program provides a succinct approach to finding the second smallest number in an array. The time complexity is O(n log n) due to the sorting operation, making it suitable for moderately sized datasets.

Output:

Second Smallest: 26

Also, learn about  Java Program to Find the Largest Number in an Array, Now!

Find the 2nd smallest number Using Collections

This Java program focuses on determining the second smallest number within an array using Java’s built-in utility classes, `Arrays` and `Collections`

// Java Program to Find 2nd Smallest Number in an Array
import java.util.*;  
public class SmallArrayEx{  
    public static int getSecondSmallest(Integer[] a, int total)
    {  
        List<Integer> list=Arrays.asList(a);  
        Collections.sort(list);  
        int element=list.get(1);  
        return element;  
    }  
    public static void main(String args[]){  
        Integer a[]={19,20,54,6,30,2};  
        System.out.println("Second Smallest: "+getSecondSmallest(a,6));
    }
}  

Explanation of the code:
After importing the necessary `java.util` package, the program defines the `SmallArrayEx` class.

Within this class, there’s a static method named `getSecondSmallest`, which takes two arguments: an array of `Integer` values `a` and the total number of elements in the array (`total`).

The method transforms the `a` array into a `List<Integer>` using `Arrays.asList(a)`. It then employs the `Collections.sort()` function to sort the list in ascending order. The second smallest element is accessed using `list.get(1)` since the list index begins from 0.

In the `main` method, an `Integer` array `a` is initialized with values. The code invokes the ‘getSecondSmallest’ method with the array and its size as arguments. Subsequently, the program retrieves the second smallest number and prints it using the `System.out.println` statement.

This approach offers a concise way to find the second smallest number using built-in utilities. Additionally, the sorting operation contributes to a time complexity of O(n log n), making it well-suited for moderately sized arrays.

Output:

Second Smallest: 6

Mastering the art of finding the smallest and second smallest numbers in an array is an essential skill for any programmer. This blog has provided insights into various methods to achieve this task in Java, showcasing how sorting, arrays, and collections can be harnessed for efficient solutions. By understanding these techniques, programmers can enhance their array manipulation skills. Additionally, they can optimize their code for better performance.

Our blog post on ‘Java Program to Find the Smallest Number in an Array’ aims to offer valuable information. For more programming-related Blogs and Courses visit our official website Newtum to make your learning easy!

About The Author

Leave a Reply