Respuesta :
Answer:
- import java.util.Arrays;
- import java.util.Scanner;
- public class DescendingOrder {
- // TODO: Write a void method selectionSortDescendTrace() that takes
- // an integer array and the number of elements in the array as arguments,
- // and sorts the array into descending order.
- public static void selectionSortDescendTrace(int [] numbers, int numElements) {
- for(int i = 0; i < numbers.length-1; i++){
- int currentMax = numbers[i];
- int index = i;
- for(int j = i + 1; j < numbers.length; j++){
- if(numbers[j] > currentMax){
- currentMax = numbers[j];
- index = j;
- }
- }
- int temp = numbers[i];
- numbers[i] = numbers[index];
- numbers[index] = temp;
- System.out.println(Arrays.toString(numbers));
- }
- }
- public static void main(String[] args) {
- Scanner scnr = new Scanner(System.in);
- int input, i = 0;
- int numElements = 0;
- int [] numbers = new int[10];
- // TODO: Read in a list of up to 10 positive integers; stop when
- // -1 is read. Then call selectionSortDescendTrace() method.
- do{
- input = scnr.nextInt();
- if(input != -1){
- numbers[i] = input;
- i++;
- numElements++;
- }
- }while(input != -1);
- selectionSortDescendTrace(numbers, numElements);
- }
- }
Explanation:
Firstly, create a do while loop to repeatedly to prompt user for number (Line 38 - 46).
Next, proceed to work on selectionSortDescendTrace method. Create a nested loop to implement selection sort logic. In outer loop, create variable currentMax and index, to track the maximum number and position of the maximum number for each iteration (Line 11 - 12). In inner loop, a current element value from array will be checked against the subsequent elements in array to identify the maximum value of that iteration (Line 13 - 17). Upon exist from the inner loop, the currentMax is swapped with the current array element indexed by i (Line 20 -21).
Print the array to console for every outer loop iteration (Line 24).