Sort numbers in Java to find minimum and maximum values without using Array
May 21
Recently a reader contacted me with a question about sorting numbers in Java. After sorting 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 the reader wanted to find largest and smallest values from a group of numbers without using Arrays. So here is another approach.
This program accepts input from the user and then prints out the largest and smallest numbers.
import java.util.*;
public class NumberSorter{
public static void main(String args[]){
double a, b, c, x, y;
Scanner console = new Scanner(System.in);
System.out.print("Enter the first number: " );
a = console.nextDouble() ;
System.out.print("Enter the second number: " );
b = console.nextDouble() ;
System.out.print("Enter the third number: " );
c = console.nextDouble();
x= Math.min(a, Math.min(b, c));
y= Math.max(a, Math.max(b, c));
System.out.println("\n" +x + " is the smallest number.\n" + y
+" is the largest number.");
}
}
Hope you find this useful. Share your ideas on how else can we find largest and smallest values from a group of numbers Java.
Related posts:



Sep 10, 2010 @ 20:08:58
Genius! I didn’t know of those methods in java, Math.min() and Math.max(); Very useful thanks for sharing.
Dec 07, 2010 @ 00:32:57
this is great! i havnt thought about this procedure.
Oct 05, 2011 @ 13:37:28
I did a course of Java and for this method i’ve learned another algorithm. This method works too.
Oct 06, 2011 @ 06:48:27
Nice article ! But I don’t think I can cope with it . LOL ! My nose is bleeding when it comes to math .
Oct 12, 2011 @ 12:50:25
we can even divide the numbers in two – two parts n use if statements to compare the larger n smaller value .. that is a much easier way to understand .. according to me !
Oct 14, 2011 @ 01:44:27
thanks i will use this script codes
Oct 27, 2011 @ 23:34:15
The following can also work:
Double[] dblArr = {a, b, c, x, y};
double x=Collections.min(Arrays.asList(dblArr));
double y = Collections.max(Arrays.asList(dblArr));