Find maximum & minimum element in array (java / example)

  • Given an array of integers , find out maximum & minimum number in array using linear search.
  • e.g. input array is { 50, 20, 63, 15, 50, 25, 85, 62, 90, 18 }
    • Minimum or smallest element is 15
    • Maximum or largest element is 90

Algorithm to find maximum & minimum element in array

  • Initialize min with maximum (largest) possible value of integer
    • We can also initialize it with first element of array.
  • Initialize the maximum with minimum (smallest) possible value
    • We can also initialize it with first element of array.
  • Start iterating through an array
    • Check min value is greater than current array element
      • min > arr[element] ?
      • yes, then update min with current array element
    • Check max value is less than current array element
      • max < arr[element] ?
      • yes, then update max with current array element
  • After we complete array iteration, we will get min and max value

Program – find largest & smallest element in an array

package org.learn.arrays;

import java.util.Arrays;

public class MaxAndMinElementInArray {

	public static void main(String[] args) {

		int arr[] = { 5, 10, 40, 35, 20 };
		String sArray = Arrays.toString(arr);
		System.out.printf("1. Minimum & Maximum value in array %s\n",sArray);
		printMinMax(arr);

		arr = new int[] { 50, 20, 63, 15, 50, 25 };
		sArray = Arrays.toString(arr);
		System.out.printf("2. Minimum & Maximum value in array %s\n",sArray);
		printMinMax(arr);

	}

	private static void printMinMax(int[] arr) {
		int min = Integer.MAX_VALUE;
		int max = Integer.MIN_VALUE;

		for (int element = 0; element < arr.length; element++) {

			if (min > arr[element])
				min = arr[element];
			if (max < arr[element])
				max = arr[element];
		}
		System.out.printf("Min value : %d & Max value: %d\n", min, max);
	}
}

Output – maximum & minimum element in an array

1. Minimum & Maximum value in array [5, 10, 40, 35, 20]
Min value : 5 & Max value: 40
2. Minimum & Maximum value in array [50, 20, 63, 15, 50, 25]
Min value : 15 & Max value: 63
Scroll to Top