Site icon

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

Algorithm to find maximum & minimum element in array

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
Exit mobile version