In this exercise, we will be looking at our example code for Selection Sort. However,…
- User
In this exercise, we will be looking at our example code for Selection Sort.
However, while we are sorting we will also count the number of swaps taking place, then print them out once the array has been sorted.
Add a print statement at the end of the selectionSort method that prints out the number of swaps that took place during the sort.
You should not modify the main() method.
Hint: Where are items compared? Try writing out the steps in the algorithm on paper to help. import java.util.Arrays;
public class SelectionSort { public static void main(String[] args) { int[] array1 = {9, 8, 7, 6, 5, 4, 3, 2, 1}; int[] array2 = {5, 6, 4, 8, 9, 7, 3, 1, 2};
System.out.print("First array: "); System.out.println(Arrays.toString(array1)); System.out.print("Second array: "); System.out.println(Arrays.toString(array2)); System.out.println(); // sort first array selectionSort(array1); // sort second array selectionSort(array2); System.out.print("First array sorted: "); System.out.println(Arrays.toString(array1)); System.out.print("Second array sorted: "); System.out.println(Arrays.toString(array2)); } /* * Selection sort takes in an array of integers and * returns a sorted array of the same integers. */ public static int[] selectionSort(int[] arr) { int currentMinIndex; for (int i = 0; i < arr.length - 1; i++) { currentMinIndex = i; for (int j = i + 1; j < arr.length; j++) { if(arr[j] < arr[currentMinIndex]) { currentMinIndex = j; } } // swap numbers if needed if (i != currentMinIndex) { int temp = arr[currentMinIndex]; arr[currentMinIndex] = arr[i]; arr[i] = temp; } } // Print out the number of swaps that took place here // before returning arr return arr; }}
- Assistant
To count the number of swaps that occur during the selection sort process, you'll need to initialize a counter before the sorting begins, and then increment this counter each time a swap occurs. Finally, print the value of this counter just before the method completes. Here's how you can make those modifications:
- User
fix the code: Test original swaps Please, try again. Expected result: 4 Your result: S est more swaps Please, try again. Expected result: 2 Your result: S
- Assistant