Sort numbers in Java to find minimum and maximum values without using Array



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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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.");
}
}
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."); } }
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.