Showing posts with label Minimum Number. Show all posts
Showing posts with label Minimum Number. Show all posts

Thursday, July 11, 2019

Find the Smallest Number in an Array Using Java


In this article, we will see how to find the smallest number from an array using java.  This is one of basic questions in technical interviews. Earlier post we had seen how to use stream for finding the missing number. Now we will see how to find the smallest number from integer array using java. 


The logic is very simple here, see the below.

  • At first we need to assume the first smallest element.
  • Then iterate over the array and compare with each element , whether its smaller than the assumed value or not. If array element is smaller then assign the array element value to assumed variable. Repeat the entire until end. 

FindSmallestNumberInArray.java

package com.techbyteslearn.lab.basic;

public class FindSmallestNumberInArray {

    // Find the smallest value from an array.
    public static void main(String[] args) {
        int[] arr = {200, 3, 4, 24, 33, 24, 22, 55, 90, 103, 150};

        // Assign the 0th index as the first smallest number.
        int smallest = arr[0];

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] <= smallest) {
                smallest = arr[i];
            }
        }

        System.out.println("Smallest Element is - " + smallest);
    }
}

Output:

Smallest Element is - 3

The original i < arr.length - 1 skips the last element. Using i < arr.length is the correct condition.



Using Java 8

IntStream.of(arr).boxed().min(Comparator.naturalOrder()).get().intValue();