Answer:
- import java.util.Arrays;
- import java.util.Scanner;
-
- public class Main {
- public static void main(String[] args) {
- int numArr [] = new int[10];
- Scanner input = new Scanner(System.in);
- System.out.print("Input number: ");
- int num = input.nextInt();
- int i = 0;
- while(num != -1){
- numArr[i] = num;
- i++;
- System.out.print("Input number: ");
- num = input.nextInt();
- }
-
- selectionSortDescendTrace(numArr);
- }
-
- public static void selectionSortDescendTrace(int [] arr){
- for(int i =0 ; i < arr.length - 1; i++){
- int largest = arr[i];
- int largeIndex = i;
-
- for(int j= i + 1; j < arr.length; j++ ){
- if(arr[j] > largest){
- largest = arr[j];
- largeIndex = j;
- }
- }
-
- int temp = arr[i];
- arr[i] = arr[largeIndex];
- arr[largeIndex] = temp;
- System.out.println(Arrays.toString(arr));
- }
- }
- }
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).