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 - 3The original
i < arr.length - 1skips the last element. Usingi < arr.lengthis the correct condition.
Using Java 8
IntStream.of(arr).boxed().min(Comparator.naturalOrder()).get().intValue();
No comments:
Post a Comment