Java Program to find the smallest number in an Array

In this post, we are going to see how to find the smallest number in an Array using core Java program.

So, here is the complete program for you (JavaSmallestInArray.java):

/**
 * @author agur
 * Find Smallest value in an array
 */
public class JavaSmallestInArray {
    public static void main(String[] args) {
        //declare an integer array
        int arr[] = {10, 20, 101, 122, 1, 5, 12};
        int temp, total, smallest;
        
        //find the total length of an array
        total = arr.length;
        
        //we have arr[0] to arr[6], check against each and find the smallest
        for (int i = 0; i < total; i++) {
            for (int j = i + 1; j < total; j++) {
                /**
                 * eg. if the array value of arr[0] is greater than arr[1] then allow
                 * otherwise just loop till find the smallest value
                 * the below code will bring the smallest value to the end of array - arr[6]                 * 
                 */
                if (arr[i] < arr[j]) {                    
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        
        //set the smallest value
        smallest = arr[total - 1];
        System.out.println("Smallest number: "+smallest);
    }
}

The output of the above program is: 

run:
Smallest number: 1

BUILD SUCCESSFUL (total time: 0 seconds)

Please go through inline comments in the above program to understand it. But the basic idea is, we are swapping the array values each time when there is the smallest number.

Here is a detailed explanation of the above program about the swapping,

//this is our array and the array length is 7
int arr[] = {10, 20, 101, 122, 1, 5, 12};

Let’s see the loop and if condition:

  1. if (a[0] < a[1]) ie., if (10 < 20) – is true, so need to swap the value
    • let’s swap, a[0] = 20, a[1] = 10
  2. if (a[1] < a[2]) ie., if (10 < 101) – is true again, so, swap the value again
    • let’s swap, a[1] = 101, a[2] = 10
  3. if (a[2] < a[3]) ie., if (10 < 122) – is true again, so, swap the value again
    • let’s swap, a[2] = 122, a[3] = 10
  4. if (a[3] < a[4]) ie., if (10 < 1) – is false, so nothing happens here
  5. if (a[4] < a[5]) ie., if (1 < 5) – is true again, so, swap the value again
    • let’s swap, a[4] = 5, a[5] = 1
  6. if (a[5] < a[6]) ie., if (1 < 12) – is true again, so, swap the value again
    • let’s swap, a[5] = 12, a[6] = 1

So, the smallest number is at the end of the array arr[6] = 1. That’s the value we are printing at the end.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top