zParacha.com

Effective programming and blogging tips by Zaheer Paracha

Subscribe:

-->
Posted by Zaheer 17 COMMENTS

minmax Three ways to find minimum and maximum values in a Java array.

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 straight forward methods to get maximum or minimum value of an array but there is a more cleaner way to do this.

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 more simpler than this. You will need to import java.util.* to use Arrays class.


Yet another way to get these values is using recursion. Today someone asked me about this and after thinking for few minutes I came up with following solution.

	public static int getMax(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 getMin(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 method.

  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 = " + getMin(numbers,0,numbers[0]));

	   //Find maximum (largest) value in array using recursion
	   System.out.println("Maximum Value = " + getMax(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 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));
	}

	//Find minimum (lowest) value in array using recursion
	private 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));
    }

}


So which method do you like the most?

Image used in this post:

ByTheTruthAbout , published under Creative Commons license CC BY-SA 2.0

Bookmark and Share

Popularity: 96% [?]

If you enjoyed this post, make sure you subscribe to my RSS feed!

Related posts:

categories: Java

17 Responses

  1. Bret says:

    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

  2. Manh Nguyen says:

    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!

  3. sree says:

    Thanks for the code. Thank you very much.

  4. Bishow says:

    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

  5. Ben says:

    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.

  6. loui says:

    galing niyo

  7. james says:

    wala bang mas mababa na code para makuha yan?

  8. Manish Sohaney says:

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

  9. Manish, I am glad you found my code useful.

  10. Code engineer says:

    Object obj Collections.max(Your Arraylist)

  11. Wolf Martinus says:

    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.

  12. sattar says:

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

  13. silver says:

    how bout a code using for-loop ?

  14. Meera says:

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

  15. Al says:

    Thanks, Saved me some time.

  16. napolion says:

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

Leave a Reply

Search

Sponsors

Get Adobe Flash playerPlugin by wpburn.com wordpress themes