Java program to find out the maximum and minimum of an array

Written by Super User. Posted in Basic

Here i am using three simple methods to find out the maximum and minimum of the array. In java we don't have any inbuilt method to find out the max and min of an array. But we have a sort method using that we can find out the max and min with one statement.

  1. Using the Simple Iteration method.
  2. Using the Sort method, sorting the array and the first element contains the min value and the last element contains the max value.
  3. Finally the method for Simple recursion method, but that uses a Ternary operator.
import java.util.Arrays;
public class maximumseries{
	public static void main(String[] args){
			int a[] = {3,5,5,1,4,5,4,33};
			System.out.println(" Using Simple Iteration");
			System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
			System.out.println("largest Number is : " + Max(a));
			System.out.println("Smallest Number is : " + Min(a));
			System.out.println("\n Using Simple Sort");
			System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
			Arrays.sort(a);
			System.out.println("largest Number is : " + a[a.length - 1]);
			System.out.println("Samllest Number is : " + a[0]);
			System.out.println("\n Using Simple Recursion");
			System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
			System.out.println("largest Number is : " + getMax(a,0,a[0]));
			System.out.println("Samllest Number is : " + getMin(a,0,a[0]));
	}
	
	public static int Max(int[] array){
		int maxval = array[0];
		for(int i = 0; i < array.length;i++){
			if(array[i] > maxval)
				maxval = array[i];
		}
		return maxval;
	}
	
	public static int Min(int[] array){
		int minval = array[0];
		for(int i = 0; i < array.length; i++){
			if(array[i] < minval)
				minval = array[i];
		}
		return minval;
	}
	public static int getMax(int[] numbers, int a, int n){  
		return a >= numbers.length ? n : Math.max(n, getMax(numbers,a+1,numbers[a]>n?numbers[a]:n));
	}  	
	public static int getMin(int[] numbers, int a, int n){
		return a==numbers.length ? n:Math.min(n,getMin(numbers,a+1,numbers[a]<n?numbers[a]:n)); 
	}
}

Out put

output for max and min of array

меня зовут эрл