Algorithms · Visualized
Tim Sort
Sorting Algorithms
Seventeen sorting algorithms on the same shuffled data — watch comparisons, swaps, pivots and heaps rearrange bars step by step.
Tim Sort is a hybrid, stable sorting algorithm that combines insertion sort and merge sort: it splits the array into small chunks called runs, sorts each run with insertion sort (which is fast on small, nearly-sorted chunks), then merges the runs bottom-up using a merge-sort-style merge. Time: O(n log n) average, O(n log n) worst; space: O(n) for the merge buffers.
Big-O: Best O(n log n) comparison sorts; counting/radix/bucket reach O(n + k) on small integer keys.
Tim Sort
SortingTim Sort is a hybrid, stable sorting algorithm that combines insertion sort and merge sort: it splits the array into small chunks called runs, sorts each run with insertion sort (which is fast on small, nearly-sorted chunks), then merges the runs bottom-up using a merge-sort-style merge. It's the default sort in Python's sorted() and Java's Arrays.sort() for objects, because real-world data often contains already-sorted runs.
How Tim Sort Works
- Split the array into runs of a fixed minimum size (here 4 elements).
- Sort each run in place with insertion sort.
- Merge pairs of adjacent sorted runs with a standard two-front merge.
- Double the merge size each round, merging larger and larger runs.
- Continue until a single sorted run spans the whole array.
Tim Sort Worked Example
Input: [5, 21, 7, 23, 19, 3, 45, 12]
Split into runs of 4: [5,21,7,23] and [19,3,45,12]. Insertion-sort each: [5,7,21,23] and [3,12,19,45]. Merge the two runs: compare fronts (5 vs 3 → take 3, 5 vs 12 → 5, 7 vs 12 → 7, 21 vs 12 → 12, …) producing [3,5,7,12,19,21,23,45].
def tim_sort(a, run=4):
n = len(a)
for start in range(0, n, run):
end = min(start + run, n)
for i in range(start + 1, end):
key = a[i]
j = i - 1
while j >= start and a[j] > key:
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
size = run
while size < n:
for left in range(0, n, 2 * size):
mid = min(left + size, n) - 1
right = min(left + 2 * size, n) - 1
if mid >= right:
continue
i, j = left, mid + 1
tmp = []
while i <= mid and j <= right:
if a[i] <= a[j]:
tmp.append(a[i]); i += 1
else:
tmp.append(a[j]); j += 1
tmp += a[i:mid + 1] + a[j:right + 1]
a[left:right + 1] = tmp
size *= 2
return aBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Tim Sort Time & Space Complexity
When to Use Tim Sort
- Python's built-in sort and Java's Collections.sort() for objects — the production default.
- Sorting real-world data that is often partially sorted (log files, timestamps, append-heavy data).
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.