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?
Bret
May 2, 2008 @ 8:39 am
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
Manh Nguyen
July 3, 2008 @ 1:22 am
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!
sree
July 8, 2008 @ 12:07 pm
Thanks for the code. Thank you very much.
Bishow
May 6, 2009 @ 5:15 pm
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
Ben
June 11, 2009 @ 2:48 am
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.
loui
August 7, 2009 @ 4:37 am
galing niyo
james
January 15, 2010 @ 3:02 am
wala bang mas mababa na code para makuha yan?
Manish Sohaney
February 21, 2010 @ 8:19 am
Thanks for the code. Your ready made solution saved my time.
Code engineer
April 1, 2010 @ 7:43 am
Object obj Collections.max(Your Arraylist)
Wolf Martinus
April 12, 2010 @ 8:19 am
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.
sattar
May 4, 2010 @ 12:57 am
yeah it was a great explanation i understood it. thanks and be success!!!!!
Sort numbers is Java to find minimum and maximum values without using Array
May 21, 2010 @ 10:27 pm
[…] 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 […]
silver
May 30, 2010 @ 7:24 am
how bout a code using for-loop ?
Meera
June 21, 2010 @ 1:12 pm
Thanks 4 solution.it helps me to save my time.
Al
July 29, 2010 @ 9:09 am
Thanks, Saved me some time.
napolion
August 24, 2010 @ 8:35 pm
teach me more about arrays cous i realy dont understand it…
help me.. im napoleon the great pretender..
SHIT
October 5, 2010 @ 5:02 am
Superb ra nee yabba…
Oneil Drummond
October 9, 2010 @ 10:50 am
Nice! help out alot but i have to remove the 36.public static int getMinValue(int[] numbers){
thanks !
Sanket Mahadik
November 14, 2010 @ 11:32 am
you give me very helpful information
thank u very much
Randy
December 12, 2010 @ 6:26 pm
Thanks so much. Very helpful. I am bookmarking this!
Jamie
December 14, 2010 @ 11:42 pm
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.
anas
January 1, 2011 @ 7:16 am
Could you please tell me that how to find Max and Min Array through recursion (data structure) ?
please send me the implementation …
worstcase
January 24, 2011 @ 2:51 am
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.
kalyan
January 26, 2011 @ 12:38 pm
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);
}
}
kalyan
January 26, 2011 @ 12:43 pm
Sorry guys for the post…Its not a complete code
kalyan
January 26, 2011 @ 12:45 pm
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);
}
kalyan
January 26, 2011 @ 12:46 pm
Sorry dont know why the data is getting truncated.
SS
February 13, 2011 @ 7:10 am
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]);
Amit Kumar
July 20, 2011 @ 8:46 pm
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);
}
}
amarnath
August 28, 2011 @ 12:45 pm
good one amazing….job
Murli Manohar Kadam
September 13, 2011 @ 4:03 am
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);
}
}
Anoop shukla
September 13, 2011 @ 4:07 am
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);
}
}
Anoop shukla
September 13, 2011 @ 4:13 am
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);
}
}
dhanush
September 14, 2011 @ 7:28 pm
great job
SeiferLeonheart
September 18, 2011 @ 6:34 pm
Thanks, had to use part of this in a assignment,helped a lot. 😀
Cheers!
iarap saba
September 29, 2011 @ 7:37 am
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.
iarap sana
September 29, 2011 @ 7:54 am
create an array of ten cells, store the value in the area at run tim. Find the largest and smallest element.
khue
October 20, 2011 @ 1:17 am
I’ve been helped a great deal. thank you all of you guys!!
Tayyeb
November 22, 2011 @ 5:38 am
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);
}
}
Parul
January 10, 2012 @ 9:36 pm
Thank you so much. Made the concept much clearer. Thanks again.
Keep up the good work. 🙂
hadi
January 11, 2012 @ 11:40 am
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
Michael Dunham
February 23, 2012 @ 1:46 pm
Thank you so much for this post, if helped me a bunch on my Java assignment for college!
sultan
February 27, 2012 @ 10:34 am
program to find minimum of four numbers using if
Eugene
March 1, 2012 @ 8:22 am
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)
jade
March 24, 2012 @ 3:44 am
java codes joptionpane maximum calculate to minimum then loop
please anybody to answer this problem. thanks give the complete codes.
M S
April 12, 2012 @ 10:29 pm
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.
Bahkale
July 12, 2012 @ 1:05 pm
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
bhordupur
September 14, 2012 @ 1:55 pm
I really like it
sefsfas
January 28, 2013 @ 4:14 pm
thank you, you saved me a lot of time and i understood the code well … thanks again
basith
March 13, 2014 @ 12:25 pm
realy thanks 🙂
basith
March 13, 2014 @ 12:26 pm
realyyyyyyyyyyyyy thanks a lotttttttttttt 🙂 🙂
Kaiviti
April 20, 2016 @ 9:29 pm
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
joane
February 16, 2017 @ 7:32 am
How will i program to find a maximum and minimum using the do_while loop
?
33Penney
May 16, 2017 @ 3:29 am
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
Sharuf
November 23, 2017 @ 3:40 pm
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();
}
}
KG
March 22, 2019 @ 5:43 am
Thanks a ton.
This is coming from a college student staying up at 1:42 am to do his CSC project.
Welp, better get back to it…