SortLab

Production hybrids · Advanced

Timsort

Find natural ordered runs, extend short ones, and merge them while preserving stability.

Best
O(n)
Average
O(n log n)
Worst
O(n log n)
Space
O(n)
Stability
Stable
Memory model
Uses auxiliary storage

How it builds order

  1. Detect ascending or descending runs.
  2. Reverse descending runs and extend short runs with insertion.
  3. Maintain a safe run stack.
  4. Stably merge neighboring runs.

Why it works

Natural runs capture existing order; stable merging combines them with the same guarantee as Merge Sort.

Watch for: Runs are the unit of work; existing order reduces how much merging is needed.

The interactive version of this page adds the full trace, synchronized pseudocode, practice decisions, input experiments, and mastery review.

Compare related strategies