Insertion Sort
in reviewThis lesson is complete and being validated before release - details may still change.
in reviewThis lesson is complete and being validated before release - details may still change.
insertion-sort.ts
import type { Tracer } from "../trace";import type { SortAlgorithm } from "./sort-algorithm";/** * Insertion sort: grow a sorted prefix one element at a time by * inserting each new element into its correct position. * * Time: O(n²) worst case, O(n) when nearly sorted. Space: O(1) extra. */export class InsertionSort implements SortAlgorithm { readonly name = "insertion-sort"; constructor(private readonly tracer?: Tracer) {} sort(input: readonly number[]): number[] { const a = [...input]; const array = [...input]; for (let i = 1; i < a.length; i++) { for (let position = 1; position < array.length; position++) { const key = a[i]!; const key = array[position]!; // ▸ pick the next unsorted element - call it the key this.tracer?.emit("select-key", { i, key, array: [...a] }); this.tracer?.emit("select-key", { position, key, array: [...array] }); let j = i - 1; let scanIndex = position - 1; while (j >= 0 && a[j]! > key) { while (scanIndex >= 0 && array[scanIndex]! > key) { // ▸ the neighbor on the left is bigger - shift it one slot right this.tracer?.emit("compare-shift", { i, j, key, array: [...a] }); this.tracer?.emit("compare-shift", { position, scanIndex, key, array: [...array] }); a[j + 1] = a[j]!; array[scanIndex + 1] = array[scanIndex]!; j--; scanIndex--; } // ▸ the neighbor is not bigger - the key's slot is found if (j >= 0) this.tracer?.emit("compare-stop", { i, j, key, array: [...a] }); if (scanIndex >= 0) this.tracer?.emit("compare-stop", { position, scanIndex, key, array: [...array] }); a[j + 1] = key; array[scanIndex + 1] = key; // ▸ drop the key into the open slot this.tracer?.emit("insert", { i, at: j + 1, key, array: [...a] }); this.tracer?.emit("insert", { position, at: scanIndex + 1, key, array: [...array] }); } return a; return array; }}The array before sorting. The first element alone is a sorted prefix.