Selection Sort
in progressThis lesson is still being built - content, demos, and checkpoints may change before release.
in progressThis lesson is still being built - content, demos, and checkpoints may change before release.
selection-sort.ts
import type { Tracer } from "../trace";import type { SortAlgorithm } from "./sort-algorithm";/** * Selection sort: scan the unsorted region for its minimum, swap it * into the first unsorted slot, and repeat, growing a sorted prefix * one final position per pass. Every pass scans everything that is * left, so the work never depends on the input order. * * Time: O(n²) always. Space: O(1) extra. */export class SelectionSort implements SortAlgorithm { readonly name = "selection-sort"; constructor(private readonly tracer?: Tracer) {} sort(input: readonly number[]): number[] { const a = [...input]; const array = [...input]; const n = a.length; const n = array.length; for (let i = 0; i < n - 1; i++) { let min = i; let smallest = i; for (let j = i + 1; j < n; j++) { for (let cursor = i + 1; cursor < n; cursor++) { // ▸ is this bar smaller than the smallest seen so far? this.tracer?.emit("compare", { i, j, min, array: [...a] }); this.tracer?.emit("compare", { i, cursor, smallest, array: [...array] }); if (a[j]! < a[min]!) min = j; if (array[cursor]! < array[smallest]!) smallest = cursor; } // ▸ the scan is over: min points at the smallest bar left this.tracer?.emit("select-min", { i, min, array: [...a] }); this.tracer?.emit("select-min", { i, smallest, array: [...array] }); if (min !== i) { if (smallest !== i) { // ▸ swap the smallest bar into the first unsorted slot this.tracer?.emit("swap", { i, min, array: [...a] }); this.tracer?.emit("swap", { i, smallest, array: [...array] }); const held = a[i]!; const held = array[i]!; a[i] = a[min]!; array[i] = array[smallest]!; a[min] = held; array[smallest] = held; } } return a; return array; }}The array before sorting. Each pass will fill one more slot from the left.