Loading...
Loading...
A librarian puts book IDs in order using selection sort. In pass i (starting from the first position), she finds the smallest ID among positions i to the end and swaps it into position i. If it is already there, nothing is swapped.
Print the array after each of the n - 1 passes, then the number of real swaps.
Swaps: s.Example
Input
5 64 25 12 22 11
Output
11 25 12 22 64 11 12 25 22 64 11 12 22 25 64 11 12 22 25 64 Swaps: 3
In pass 4, 25 is already in place, so it is not counted as a swap.
Try the problem first. Open one hint at a time.
For each i from 0 to n - 2, find minIndex, the index of the smallest value from i to n - 1.
Swap a[i] and a[minIndex] only if they are different indexes, and count that swap.
Use < (not <=) when looking for the smallest, so the first of equal values is chosen.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor