Write the following function to sort three numbers in increasing order. num1, nu
ID: 3654698 • Letter: W
Question
Write the following function to sort three numbers in increasing order. num1, num2, num3 are pass-by-reference parameters. The values of num1, num2, num3 are changed to sorted increasing order at the end of function sort. So if n1, n2, n3 have values 3, 1, 2 respectively, then the function call: sort(n1,n2,n3) will change the values of n1, n2, n3 to: 1, 2, 3 respectively. Note that you must implement num1, num2, num3 as pass-by-reference parameters and swap their values if they are not in sorted increasing order. void sort(double &num1;, double &num2;, double &num3;) Write a test program, TestSort, which tests the implementation of function sort. It uses three variables to call function sort and display the sorted result. This program must call sort 6 times to check sorting of the following 6 sequences of numbers. Your program can either use a loop and one function call to read these numbers from user input or not use a loop but write 6 function calls. Note that you must display the sorted result outside function sort and inside main(). 1, 2, 3 1, 3, 2 2, 1, 3 2, 3, 1 3, 1, 2 3, 2, 1 Place the definition of function sort in the test program TestSort.Explanation / Answer
import java.util.Scanner;
public class Prog17 {
public static void main(String[] args) {
//Create a scanner
Scanner input = new Scanner(System.in);
//Prompt the user to enter three numbers, in double
System.out.print("Enter the first number: ");
double num1 = input.nextDouble();
System.out.print("Enter the second number: ");
double num2 = input.nextDouble();
System.out.print("Enter the third number: ");
double num3 = input.nextDouble();
System.out.println("The numbers in ascending order are: ");
displaySortedNumbers(num1, num2, num3);
}
//Put the numbers in order
public static void displaySortedNumbers(double num1, double num2, double num3) {
if ( (num1 < num2) && (num1 < num3) ) {
System.out.print(num1);
if (num2 < num3)
System.out.println(" " + num2 + " " + num3);
else
System.out.println(" " + num3 + " " + num2);
}
else if ( (num2 < num1) && (num2 < num3) ) {
System.out.print(num2);
if (num1 < num3)
System.out.println(" " + num1 + " " + num3);
else
System.out.println(" " + num3 + " " + num1);
}
else if ( (num3 < num1) && (num3 < num2) ) {
System.out.print(num3);
if (num1 < num2)
System.out.println(" " + num1 + " " + num2);
else
System.out.println(" " + num2 + " " + num1);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.