In: Computer Science
IN JAVA
Methods**: Sort three values
Write a method Ascend3 with an array of integers of size three as the parameter, that sorts the values of the array into ascending order. Ex: If the array contains [5, 2, 7], after the call Ascend3(int[] vals), the array will now hold [2, 5, 7].
Hints:
Return type should be void.
One approach puts the three values into an array, then sorts the array. We won't be describing that approach here. Instead, we'll use branches.
One solution approach realizes that only 6 possible orderings of xyz exist: xyz, xzy, yxz, yzx, zxy, zyx. An if-else can be used to detect which order x, y, z are initially in.
Once detected, three variables lowVal, midVal, and highVal can be assigned. Note: Don't assign the parameter right away, because you'll overwrite a value that is still needed.
After the if-else, those lowVal, midVal, and highVal variables are ready. So just set the vals[0] with lowVal, vals[1] with midVal, and vals[2] with highVal.
Be aware that two values could be equal. So use <= rather than < in your comparisons.
GIVEN CODE:
import java.util.Scanner;
public class Main {
// Define Ascend3() here
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int[] arrVals = new int[3];
arrVals[0] = scnr.nextInt(); // x
arrVals[1] = scnr.nextInt(); // y
arrVals[2] = scnr.nextInt(); // z
Ascend3(arrVals);
System.out.println(arrVals[0] + " " + arrVals[1] + " " +
arrVals[2]);
}
}
import java.util.Scanner;
public class Main {
/**
* method that receives an array of integers of size 3
and sorts the values into ascending order
*/
public static void Ascend3(int vals[])
{
int lowVal, midVal, highVal;
// if-else statements to get the
low,mid and high values
if(vals[0] <= vals[1]) //
vals[0] <= vals[1]
{
if(vals[0] <=
vals[2]) // if vals[0] <= vals[2]
{
lowVal = vals[0];
// vals[0] <= vals[1] <= vals[2]
if(vals[1] <= vals[2]) // 0,1,2
{
midVal = vals[1];
highVal = vals[2];
}
// vals[0] <= vals[2] <= vals[1]
else
// 0,2,1
{
midVal = vals[2];
highVal = vals[1];
}
}
// vals[2] <=
vals[0] <= vals[1]
else
// 2,0,1
{
lowVal = vals[2];
midVal = vals[0];
highVal = vals[1];
}
}else // vals[1] <=
vals[0]
{
// vals[1] <=
vals[2]
if(vals[1] <=
vals[2])
{
lowVal = vals[1];
// vals[1] <= vals[0] <= vals[2]
if(vals[0] <= vals[2]) //
1,0,2
{
midVal = vals[0];
highVal = vals[2];
}
// vals[1] <= vals[2] <= vals[0]
else
//
1,2,0
{
midVal = vals[2];
highVal = vals[0];
}
}
// vals[2] <=
vals[1] <= vals[0]
else
// 2,1,0
{
lowVal = vals[2];
midVal = vals[1];
highVal = vals[0];
}
}
// set the values in the array in
sorted order
vals[0] =lowVal;
vals[1] = midVal;
vals[2] = highVal;
}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int[] arrVals = new int[3];
arrVals[0] = scnr.nextInt(); // x
arrVals[1] = scnr.nextInt(); // y
arrVals[2] = scnr.nextInt(); // z
Ascend3(arrVals);
System.out.println(arrVals[0] + " " + arrVals[1] + " " +
arrVals[2]);
}
}
//end of program
Output: