108k views
4 votes
Write a void method selectionSortDescendTrace() that takes an integer array, and sorts the array into descending order. The method should use nested loops and output the array after each iteration of the outer loop, thus outputting the array N-1 times (where N is the size). Complete main() to read in a list of up to 10 positive integers (ending in -1) and then call the selectionSortDescendTrace() method. If the input is: 20 10 30 40 -1 then the output is: 40 10 30 20 40 30 10 20 40 30 20 10

User Meighan
by
6.6k points

1 Answer

4 votes

Answer:

  1. import java.util.Arrays;
  2. import java.util.Scanner;
  3. public class Main {
  4. public static void main(String[] args) {
  5. int numArr [] = new int[10];
  6. Scanner input = new Scanner(System.in);
  7. System.out.print("Input number: ");
  8. int num = input.nextInt();
  9. int i = 0;
  10. while(num != -1){
  11. numArr[i] = num;
  12. i++;
  13. System.out.print("Input number: ");
  14. num = input.nextInt();
  15. }
  16. selectionSortDescendTrace(numArr);
  17. }
  18. public static void selectionSortDescendTrace(int [] arr){
  19. for(int i =0 ; i < arr.length - 1; i++){
  20. int largest = arr[i];
  21. int largeIndex = i;
  22. for(int j= i + 1; j < arr.length; j++ ){
  23. if(arr[j] > largest){
  24. largest = arr[j];
  25. largeIndex = j;
  26. }
  27. }
  28. int temp = arr[i];
  29. arr[i] = arr[largeIndex];
  30. arr[largeIndex] = temp;
  31. System.out.println(Arrays.toString(arr));
  32. }
  33. }
  34. }

Step-by-step explanation:

The solution code is written in Java.

First, we work on the selectionSortDescendTrace method that takes one input array (Line 21). In the method, we create a nested loops. In the outer loop, we set the current element indexed by i as the largest value and use another variable largeIndex to track the index of largest value (Line 23 -24).

We create inner loop to traverse through the subsequent number after current index-i and compared each of the element by the current largest value (Line 26 - 30). If any of the subsequent element is larger than the current largest value, set the element as largest value and update the largeIndex accordingly (Line 27 - 29).

After completion of inner loop, we swap the position of the current found largest number with the element indexed by current i (Line 33 - 35). Print the partially sorted array (Line 36).

User John Saunders
by
7.0k points