Bubble 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.
bubble-sort.ts
import type { Tracer } from "../trace";import type { SortAlgorithm } from "./sort-algorithm";/** * Bubble sort: sweep the unsorted prefix left to right, swapping each * pair of neighbors that is out of order. Every sweep carries the * largest remaining value to the end of the prefix, and a sweep with * no swaps proves the array sorted, so the sort stops early. * * Time: O(n²) worst and average, O(n) when already sorted. Space: O(1) extra. */export class BubbleSort implements SortAlgorithm { readonly name = "bubble-sort"; constructor(private readonly tracer?: Tracer) {} sort(input: readonly number[]): number[] { const a = [...input]; const array = [...input]; for (let end = a.length - 1; end >= 1; end--) { for (let unsortedEnd = array.length - 1; unsortedEnd >= 1; unsortedEnd--) { let swapped = false; for (let j = 0; j < end; j++) { for (let cursor = 0; cursor < unsortedEnd; cursor++) { // ▸ compare this pair of neighbors this.tracer?.emit("compare", { end, j, array: [...a] }); this.tracer?.emit("compare", { unsortedEnd, cursor, array: [...array] }); if (a[j]! > a[j + 1]!) { if (array[cursor]! > array[cursor + 1]!) { // ▸ the left one is bigger, swap them this.tracer?.emit("swap", { end, j, array: [...a] }); this.tracer?.emit("swap", { unsortedEnd, cursor, array: [...array] }); const held = a[j]!; const held = array[cursor]!; a[j] = a[j + 1]!; array[cursor] = array[cursor + 1]!; a[j + 1] = held; array[cursor + 1] = held; swapped = true; } } // ▸ the sweep is over, its largest value is in place this.tracer?.emit("pass-done", { end, swapped, array: [...a] }); this.tracer?.emit("pass-done", { unsortedEnd, swapped, array: [...array] }); if (!swapped) break; } return a; return array; }}The array before sorting: bubble sort will sweep it left to right, comparing each bar with its right-hand neighbor.