Final answer:
The DescendingOrder class needs a selectionSortDescendTrace method that sorts an integer array in descending order and prints the array after each outer loop iteration. In the main method, the code reads up to 10 integers, ends with -1, and invokes the sorting method.
Step-by-step explanation:
The student is tasked with implementing a selection sort algorithm in Java that sorts an array into descending order and prints the array after each pass of the outer loop. The method selectionSortDescendTrace must be written within the DescendingOrder class. In main(), a list of up to 10 positive integers is to be read in and processed by the sorting method, with -1 signaling the end of input.
Implementation of selectionSortDescendTrace Method:
Below is a suitable implementation for the requested method:
public static void selectionSortDescendTrace(int [] numbers, int numElements) {
for (int i = 0; i < numElements - 1; i++) {
// Find index of the maximum element
int indexMax = i;
for (int j = i + 1; j < numElements; j++) {
if (numbers[j] > numbers[indexMax]) {
indexMax = j;
}
}
// Swap the found maximum element with the first element
int temp = numbers[i];
numbers[i] = numbers[indexMax];
numbers[indexMax] = temp;
// Printing the current state of the array
for (int k = 0; k < numElements; k++) {
System.out.print(numbers[k] + " ");
}
System.out.println();
}
}
Modification of the main Method:
To read the integers and call the sorting function, the main method could look like this:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int input, i = 0;
int[] numbers = new int[10];
while (i < 10 && (input = scnr.nextInt()) != -1) {
numbers[i++] = input;
}
selectionSortDescendTrace(numbers, i);
}
This code will take user input, store it into an array, and then call the sorting algorithm to sort and print the array in descending order.