AlgoFrames

Selection sort of pairs by key

Challenge · Write code · about 15 min

Each pair in pairs is [key, id]. Sort the pairs by key in ascending order with a selection sort, and keep pairs with equal keys in their input order (a stable sort).

A plain swap breaks the tie order, so move the minimum into place without swapping it past equal keys.

Example 1

Input:

[[[3,0],[3,1],[1,2],[2,3]]]

Output:

[[1,2],[2,3],[3,0],[3,1]]

Plain swaps would give [1, 2], [2, 3], [3, 1], [3, 0].

Example 2

Input:

[[[2,0],[1,1]]]

Output:

[[1,1],[2,0]]

Constraints

  • 0 ≤ pairs.length ≤ 1,000
  • 0 ≤ key ≤ 1,000
  • ids are distinct

Learn the idea first: Selection sort, a visual lesson.

More Selection sort problems