Selection sort in place and return the number of swaps
Selection sort does very few writes: at most one swap per position. That makes it a reasonable choice when moving an item is expensive, for example reordering cards on a physical kanban board or rewriting rows on slow storage. Your task is to implement it and report how many swaps it made.
Implement selectionSortSwaps(array, compare). It sorts array in place in ascending order and returns the number of swaps it performed.
selectionSortSwaps(array, compare?) // => number of swaps
Follow these steps exactly, because the tests check both the final order and the swap count:
i from 0 to array.length - 2, find the smallest element in array[i..end].i, swap it with array[i] and count one swap. If it is already at i, do nothing.compare(a, b) returns a negative number when a comes before b, a positive number when it comes after, and 0 when they tie.compare is omitted, compare numbers by value (a - b).const pages = [3, 1, 2];
selectionSortSwaps(pages); // => 2
pages; // => [1, 2, 3]
selectionSortSwaps([5, 4, 3, 2, 1]); // => 2 (swap 5/1, then 4/2)
selectionSortSwaps([1, 2, 3]); // => 0
selectionSortSwaps([]); // => 0
const cards = [
{ name: 'Design', points: 5 },
{ name: 'Review', points: 5 },
{ name: 'Hotfix', points: 1 },
];
selectionSortSwaps(cards, (a, b) => a.points - b.points); // => 1
cards.map((card) => card.name); // => ['Hotfix', 'Review', 'Design']
In the last example, the first pass swaps Hotfix with Design. In the second pass, Review and Design tie, and Review is leftmost and already in place, so nothing moves. Selection sort is not stable, and that is expected.
Array.prototype.sort or Array.prototype.toSorted.