Selection SortLoading saved progress…

Selection Sort

Implement selectionSort(array) — order an array of numbers ascending using selection sort. The idea is simple: repeatedly find the smallest value in the part of the array you haven't sorted yet, and move it to the front of that unsorted part. After the first pass the smallest value sits at index 0; after the second, the next smallest sits at index 1; and so on until the whole array is in order. Return a new sorted array — do not change the array you were given.

Signature

// array:   number[]   — the numbers to sort (not mutated).
// returns: number[]    — a NEW array with the same values, sorted ascending.
function selectionSort(array: number[]): number[];

Examples

selectionSort([3, 1, 2]);
// → [1, 2, 3]
selectionSort([64, 25, 12]);
// → [12, 25, 64]

Notes

  • Sort a copy. The input array must be unchanged after the call. Build and return a fresh array; the caller still holds their original order.
  • Return a new reference. Even if the input is already sorted, return a different array object — not the same one you were handed.
  • Ascending, numeric. Order from smallest to largest by numeric value. Negative numbers and duplicates are allowed and must be handled.
  • Edge cases. An empty array returns []; a single-element array returns a copy of itself. Already-sorted and reverse-sorted inputs must both come out sorted.
  • No built-in sort. The point is to implement the algorithm by hand, so don't reach for Array.prototype.sort.
Loading editor…