Find Largest and Smallest number in Array

Find minimum and maximum number in array

Given a integer array, find minimum and maximum number in array. Lets understand the problem statement graphically and it will be more clear,

Algorithm


There are many approach to solve this problem, Lets see one of the efficient way.
  1. Take 2 variable "min" and "max" and initialize min to largest value and max to smallest value.
    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;
  2. Iterate through array and
    if the current value is > max then update max with new maximum value.

    if the current value is < min then update min with new minimum value.

Java Program to find Minimum and Maximum number in array.


public class FindLargestSmallestNumberArray {

 public static void main(String[] args) {
  int[] arr = new int[]{10,1,2,8,3,15,3};
  findLargestSmallestNumberArray(arr);
 }
 
 private static void findLargestSmallestNumberArray(int[] arr){
  if(arr==null || arr.length < 1){
   return;
  }
  int min = Integer.MAX_VALUE;
  int max = Integer.MIN_VALUE;
  
  for (int value : arr) {
   if(value < min){
    min = value;
   }
   if(value > max){
    max = value;
   }
  }
  System.out.println("Minimum element :"+min);
  System.out.println("Maximum element :"+max);
 }
}


You may also like to see


Find Largest, Second Largest, Smallest and Second Smallest number in array

Count zeros in a row wise and column wise sorted matrix

Find middle element of a linked list

Union and Intersection of Two Sorted Arrays

Merge two sorted arrays in Java

How is ambiguous overloaded method call resolved in java


Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

Post a Comment