11 July, 2019

Find smallest number in array 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.javadevelopersguide.lab.basic;
/**
 * This program illustrate how to find the smallest number from an array.
 *
 * @author manoj.bardhan
 *
 */
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 };
// Assigning 0th index as first smallest number to proceed the program.
int smallest = arr[0];
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] <= smallest) {
smallest = arr[i];
}
}
System.out.println("Smallest Element is - " + smallest);
}
}

Output - 

Smallest Element is - 3 

Using Java 8

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



No comments:

Post a Comment