Three ways to find minimum and maximum values in a Java array of primitive types.



In Java you can find maximum or minimum value in a numeric array by looping through the array. Here is the code to do that.

public static int getMaxValue(int[] numbers){
  int maxValue = numbers[0];
  for(int i=1;i < numbers.length;i++){
    if(numbers[i] > maxValue){
	  maxValue = numbers[i];
	}
  }
  return maxValue;
}

public static int getMinValue(int[] numbers){
  int minValue = numbers[0];
  for(int i=1;i<numbers.length;i++){
    if(numbers[i] < minValue){
	  minValue = numbers[i];
	}
  }
  return minValue;
}

These are very straightforward methods to get the maximum or minimum value of an array but there is a cleaner way to do this.

Using Arrays.sort method to Find Maximum and Minimum Values in an Array

 

int[] nums={6,-1,-2,-3,0,1,2,3,4};
Arrays.sort(nums);
System.out.println("Minimum = " + nums[0]);
System.out.println("Maximum = " + nums[nums.length-1]);

You cannot make it simpler than this. You will need to import java.util.* to use Arrays class.

Using Recursion to Find Maximum and Minimum Values in an Array

Yet another way to get these values is using recursion.

Following methods show how to use recursion to find maximum and minimum values of an array.

public static int getMaximumValueUsingRecursion(int[] numbers, int a, int n){
  return a>=numbers.length?n:Math.max(n,max(numbers,a+1,numbers[a]>n?numbers[a]:n));
  }
 private static int getMinimumValueUsingRecursion(int[] numbers, int a, int n) {
     return a==numbers.length?n:Math.min(n,min(numbers,a+1,numbers[a]<n?numbers[a]:n));
 }

 

Here is an executable Java class demonstrating the use of all three methods.

  import java.util.Arrays;
  public class MinMaxValues{

	public static void main (String args[]){
	   int numbers[]= {1,5,-9,12,-3,89, 18,23,4,-6};
	   //Find minimum (lowest) value in array using loop
	   System.out.println("Minimum Value = " + getMinValue(numbers));
	   //Find maximum (largest) value in array using loop
	   System.out.println("Maximum Value = " + getMaxValue(numbers));

	    //Find minimum (lowest) value in array by sorting array
	   System.out.println("Minimum Value = " + minValue(numbers));
	   //Find maximum (largest) value in array by sorting array
	   System.out.println("Maximum Value = " + maxValue(numbers));

	   //Find minimum (lowest) value in array using recursion
	   System.out.println("Minimum Value = " + getMinimumValueUsingRecursion(numbers,0,numbers[0]));

	   //Find maximum (largest) value in array using recursion
	   System.out.println("Maximum Value = " + getMaximumValueUsingRecursion(numbers,0,numbers[0]));

	}

	//Find maximum (largest) value in array using loop
	public static int getMaxValue(int[] numbers){
		int maxValue = numbers[0];
		for(int i=1;i<numbers.length;i++){
			if(numbers[i] > maxValue){
				maxValue = numbers[i];
			}
		}
		return maxValue;
	}

	//Find minimum (lowest) value in array using loop
	public static int getMinValue(int[] numbers){
		int minValue = numbers[0];
		for(int i=1;i<numbers.length;i++){
			if(numbers[i] < minValue){
				minValue = numbers[i];
			}
		}
		return minValue;
	}

	//Find minimum (lowest) value in array using array sort
	public static int minValue(int[] numbers){
	  Arrays.sort(numbers);
	  return numbers[0];
	}

	//Find maximum (largest) value in array using array sort
	public static int maxValue(int[] numbers){
	  Arrays.sort(numbers);
	  return numbers[numbers.length-1];
	}

	//Find maximum (largest) value in array using recursion
	public static int getMaximumValueUsingRecursion(int[] numbers, int a, int n){
		return a>=numbers.length?n:Math.max(n,getMax(numbers,a+1,numbers[a]>n?numbers[a]:n));
	}

	//Find minimum (lowest) value in array using recursion
	private static int getMinimumValueUsingRecursion(int[] numbers, int a, int n) {
     return a==numbers.length?n:Math.min(n,getMin(numbers,a+1,numbers[a]<n?numbers[a]:n));
    }

}


So which method do you like the most?

Comments 55

  • I really appreciate the fact you take the time to write about something that others “assume” everyone knows. Quick useful posts such as this really help more people than you might imagine. Keep them coming.

    Bret’s last blog post..Friday Finds for 05/02/2008: Online RAID Space Calculation

  • Thanks for your code above, in my case, i have to find them from the list of integer input from keyboard.
    Have you solutions help me.

    Best regards!

  • Thanks for the code. Thank you very much.

  • I am just surprised why your code has Case difference in the upper box and the lower boxes. Couldn’t get ther result that way

  • Interesting – but of course the sort does more than merely find the maximum and minimum, and also involves correspondingly more work. Obviously, this is most relevant when the operation is to be used many thousands of times a second.

  • wala bang mas mababa na code para makuha yan?

  • Thanks for the code. Your ready made solution saved my time.

  • Object obj Collections.max(Your Arraylist)

  • Your version of the straight iteration is a bit convoluted:

    int getMax(int[] numbers) {
    int max= Integer.MIN_VALUE;
    for (int i : numbers)
    max = Math.max(max, i);
    return max;
    }

    And the straight iteration is in fact the most efficient method, as using sort uses n*log(n) time and the recursive variant uses more resources on the stack.

  • yeah it was a great explanation i understood it. thanks and be success!!!!!

  • […] the number the program then needs to print the largest and smallest values. I have written a post earlier that shows one way of finding largest and smallest numbers. That approach used Arrays but […]

  • how bout a code using for-loop ?

  • Thanks 4 solution.it helps me to save my time.

  • Thanks, Saved me some time.

  • teach me more about arrays cous i realy dont understand it…
    help me.. im napoleon the great pretender..

  • Superb ra nee yabba…

  • Nice! help out alot but i have to remove the 36.public static int getMinValue(int[] numbers){

    thanks !

  • you give me very helpful information
    thank u very much

  • Thanks so much. Very helpful. I am bookmarking this!

  • Thank you very much for taking the time to post these methods. I must have gone through 3 different wordings of my search in google and 20 different websites before I found this website. The previous 20 websites were just forums full of non-helpful people that assume everyone knows this and use lots of jargon that basically makes this far more complicated than needed.

  • Could you please tell me that how to find Max and Min Array through recursion (data structure) ?

    please send me the implementation …

  • in case you have to consider performance do not use sort, because this runs in O(n log n) time.
    Collections.max should be prefered.

  • Used to get the Max and Min of integer array in one Iteration.

    public class TestMinMaxIntegerArray {

    /**
    * @param args
    */
    public static void main(String[] args) {
    int[] xx = { -3, 0,10, 1, 1 };
    int min = 0;
    int max = 0;
    int tempMax = 0;
    int tempMin = 0;
    boolean flag = true;
    for (int i = 0, j = 1; j < xx.length; i++, j++) {
    if (xx[i] min) {
    tempMin = min;
    }
    if (tempMax < max) {
    tempMax = max;
    }

    }
    System.out.println("MAX:" + tempMax + " " + "MIN:" + tempMin);

    }

    }

  • Sorry guys for the post…Its not a complete code

  • public static void main(String[] args) {
    int[] xx = { -3, 0,10, 1, 1 };
    int min = 0;
    int max = 0;
    int tempMax = 0;
    int tempMin = 0;
    boolean flag = true;
    for (int i = 0, j = 1; j < xx.length; i++, j++) {
    if (xx[i] min) {
    tempMin = min;
    }
    if (tempMax < max) {
    tempMax = max;
    }

    }
    System.out.println("MAX:" + tempMax + " " + "MIN:" + tempMin);

    }

  • Sorry dont know why the data is getting truncated.

  • Sorry, but I think I need some help here.. I can’t seems to get the minimum value but I can get the maximum value for my programme. Is this the complete code or something? Or you can somehow help me check through my programme on why I can’t get the desire result..?

    int[] nums={6,-1,-2,-3,0,1,2,3,4};
    Arrays.sort(nums);
    System.out.println(“Minimum = ” + nums[0]);
    System.out.println(“Maximum = ” + nums[nums.length-1]);

  • This is the working code:

    import java.io.*;
    class maxx_minn
    {
    public static void main(String ags [ ])throws IOException
    {
    int i,max,min,num;

    BufferedReader br= new BufferedReader
    (new InputStreamReader (System.in));

    i=1;
    max=0;
    min=2^31-1;

    while(i<=10)
    {
    System.out.println("Enter a number");
    num= Integer.parseInt (br.readLine());
    if(maxnum)
    min=num;
    i++;
    }
    System.out.println(“THE MAXIMUM NUMBER IS:”+max);
    System.out.println(“THE MINIMUM NUMBER IS:”+min);
    }
    }

  • good one amazing….job

  • import java.util.* ;
    class min
    {
    public static void main(String a1[])
    {
    Scanner in=new Scanner(System.in);
    int i,mn=0,mx=0,a[];
    a=new int[5];
    System.out.println(“Enter elements of array”);
    for(i=0;i<a.length;i++)
    {
    a[i]=in.nextInt();
    if(mx<a[i])
    {
    mx=a[i];
    }
    }
    mn=mx;
    for(i=0;ia[i])
    {
    mn=a[i];
    }
    }
    System.out.println(“min = “+mn);
    }
    }

  • import java.util.* ;
    class min
    {
    public static void main(String a1[])
    {
    Scanner in=new Scanner(System.in);
    int i,min=0,max=0,a[];
    a=new int[5];
    System.out.println(“Enter elements of array”);
    for(i=0;i<a.length;i++)
    {
    a[i]=in.nextInt();
    if(max<a[i])
    {
    max=a[i];
    }
    }
    min=max;
    for(i=0;ia[i])
    {
    min=a[i];
    }
    }
    System.out.println(“maxmium =”+max);
    System.out.println(“miniumum = “+min);
    }
    }

  • import java.util.* ;
    class min
    {
    public static void main(String a1[])
    {
    Scanner in=new Scanner(System.in);
    int i,min=0,max=0,a[];
    a=new int[5];
    System.out.println(“Enter elements of array”);
    for(i=0;i<a.length;i++)
    {
    a[i]=in.nextInt();
    if(max<a[i])
    {
    max=a[i];
    }
    }
    min=max;
    for(i=0;ia[i]);
    min=a[i];
    }
    }
    System.out.println(“maxmium =”+max);
    System.out.println(“miniumum = “+min);
    }
    }

  • Thanks, had to use part of this in a assignment,helped a lot. 😀

    Cheers!

  • please provide me the following source code of java Programming.
    Create an Array of ten cells, store the value in the area at run time. Find the find the largest and smallest element.

  • create an array of ten cells, store the value in the area at run tim. Find the largest and smallest element.

  • I’ve been helped a great deal. thank you all of you guys!!

  • import java.util.Scanner;
    public class Array {
    public static void main(String[]args)
    {
    int [][]marks=new int [2][2];
    fillArray(marks,2,2);
    max(marks,2,2);
    }
    public static void fillArray(int mmarks[][],int row ,int coloumn){
    int k=0;
    Scanner input=new Scanner(System.in);
    for (int i = 0; i < row ; i++){
    for(int j=0 ; j < coloumn ; j++){
    k=k+1;
    System.out.println("Enter marks"+k);
    mmarks[i][j]=input.nextInt();

    }

    }

    }
    public static void max(int mnmarks[][],int nrow,int ncoloumn){
    int maxValue=mnmarks[0][0];
    for (int i = 0; i < nrow ; i++){
    for (int j = 0 ; j maxValue){
    maxValue=mnmarks[i][j];
    }

    }
    }

    System.out.println(“highest=”+maxValue);
    }
    }

  • Thank you so much. Made the concept much clearer. Thanks again.
    Keep up the good work. 🙂

  • hi
    i need some information about testing c programming
    is anybody can help me what i have to do?
    i have my program but i donot know where i have to test it
    many thanks

  • Thank you so much for this post, if helped me a bunch on my Java assignment for college!

  • program to find minimum of four numbers using if

  • Lets say if i want to show a maximum value , and there is an array of x[] = {10,20,30,40,40,40,30,20,10};
    assuming each data is month 1 to 9
    i wan to show the maximum value is 40 in months (4,5,6)

  • java codes joptionpane maximum calculate to minimum then loop
    please anybody to answer this problem. thanks give the complete codes.

  • Sorting just to find the min and max destroys your data integrity and takes longer to run than just searching. The sort will be O(n log n) and the search would have been O(n). The fact you destroy the original order of the data is not to be assumed okay.

  • Gr8 deal guyz.. I lyk diz stuffs.. Bt i want some 1 to help me with the code: to store 100 different numbers and calculate the difference between max nd Min of those numbers

  • I really like it

  • thank you, you saved me a lot of time and i understood the code well … thanks again

  • realy thanks 🙂

  • realyyyyyyyyyyyyy thanks a lotttttttttttt 🙂 🙂

  • import java.util.Scanner;

    class exam
    {
    public static void main(String[] args)
    {
    Scanner input = new Scanner(System.in);

    System.out.println(“Enter 5 numbers:”);

    int[] numbers = new int[5];
    int sum = 0;
    int max = numbers[0];
    int min = numbers[0];

    for(int i=0; i max){
    max = numbers[i];
    }
    else if (numbers[i] < min){
    min = numbers[i];
    }

    }

    int average = sum / 5;

    System.out.println("Sum: " + sum);
    System.out.println("Average: " + average);
    System.out.println("Max: " + max);
    System.out.println("Min: " + min );
    }
    }

    How come my "min" is always displaying "0"…Please can someone help me…Thanks

  • How will i program to find a maximum and minimum using the do_while loop
    ?

  • I must say it was hard to find your page in search results.
    You write great articles but you should rank your
    page higher in search engines. If you don’t know how
    to do it search on youtube: how to rank a website Marcel’s
    way

  • Yours is too tough.You guys can check mine..
    import java.util.Scanner;

    public class Array {

    public static void Max() {
    int i;

    int sum = 0;
    double avg = 0;
    Scanner input = new Scanner(System.in);
    System.out.printf(“%s %s\n”, “Index”, “Value”);
    int[] a = new int[4];

    for (i = 0; i < a.length; i++) {
    a[i] = input.nextInt();

    sum += a[i];

    }

    int d = Math.max(Math.max(a[0], a[1]), Math.max(a[2], a[3]));
    int e = Math.min(Math.min(a[0], a[1]), Math.min(a[2], a[3]));

    avg = sum / i;

    System.out.printf(" sum is %d\nAvg is %f\nMaximum is %d\nMinimum is %d", sum, avg, d, e);

    }

    public static void main(String[] args) {
    Array obj = new Array();
    obj.Max();
    }

    }

Leave a Reply

Your email address will not be published. Required fields are marked *