Skip to content

Bubble sort ​

The module offers two imported functions. bubbleSort(values) returns an ascending copy for direct use, while bubbleSortInfo(values) returns independent input/output snapshots and semantic counters for studying the algorithm. Neither function changes the input array.

Direct execution ​

SignatureReturnsComplexity
bubbleSort(values: i32[])i32[]O(n²) worst and average case, O(n) best case
tyrus
import { bubbleSort } from "tyrus:algorithm";
const sorted: i32[] = bubbleSort([2, 4, 1, 3]);
print(sorted); // [1, 2, 3, 4]

Study result ​

ExportKindPurpose
bubbleSortInfo(values: i32[])FunctionReturns a BubbleSortInfo without changing values
BubbleSortInfoData interfaceHolds the Bubble Sort snapshots and all metrics
tyrus
interface BubbleSortInfo {
    originalValues: i32[];
    sortedValues: i32[];
    comparisonCount: usize;
    swapCount: usize;
    passCount: usize;
}

BubbleSortInfo exposes originalValues: i32[], sortedValues: i32[], comparisonCount: usize, swapCount: usize, and passCount: usize. The arrays are independent snapshots of the input and sorted output.

tyrus
import { BubbleSortInfo, bubbleSortInfo } from "tyrus:algorithm";

const input: i32[] = [4, 1, 3, 2];
const info: BubbleSortInfo = bubbleSortInfo(input);

print(input); // [4, 1, 3, 2]
print(info.originalValues); // [4, 1, 3, 2]
print(info.sortedValues); // [1, 2, 3, 4]
print(info.comparisonCount); // 6
print(info.swapCount); // 4
print(info.passCount); // 3

Metric definitions ​

  • comparisonCount increments once for every adjacent pair evaluated by the inner loop.
  • swapCount increments once when an adjacent comparison exchanges two values.
  • passCount increments after each completed traversal of the current unsorted prefix, including the final traversal that performs no swap and stops early.
  • Empty and single-element inputs perform zero comparisons, swaps, and passes.

Bubble Sort is stable because equal values are never exchanged. The instrumented variant has the same O(n²) worst-case and O(n) best-case running time as the direct function, plus O(n) result storage for the original and sorted snapshots. Static characteristics such as stability and complexity remain in this documentation instead of being repeated in every result value. The current API intentionally accepts only i32[].