Apex › Storage & databases

The sort in your standard library (Timsort)

The adaptive, stable hybrid that’s the default sort in Python, Java, Rust, and Swift. Real data has already-sorted stretches, so Timsort finds natural runs (ascending, or descending reversed), extends short ones with binary insertion sort, and merges runs in a balanced stack order — switching to galloping (binary-search + bulk copy) when one run dominates. Sorted input is one run → O(n); random → O(n log n); equal keys keep their order (stable). Verified in node: output matches a reference sort, it’s stable, and it makes ~5× fewer comparisons on sorted vs random input. Feed it different data shapes and watch the runs.

More in Storage & databases