COMPARISON SORTS
Tim Sort, visualised
Tim sort combines insertion sort and merge sort. This app visualises a simplified version: it insertion-sorts fixed runs of 8 elements and then merges the runs.
Run Tim Sort in the visualizer →
Opens the Sorting Cinema visualizer with 16 elements in English.
How it works
- Split the array into runs of 8 elements from the front (this app's implementation).
- Sort each run with insertion sort.
- Merge neighbouring runs, doubling the length of sorted runs each round.
- When one run covers the whole array, it is sorted.
Complexity and stability
- Best
- O(n log n)
- Average
- O(n log n)
- Worst
- O(n log n)
- Extra space
- O(n)
- Stability
- Stable
This simplified version does 8-element insertion sorts (O(n) overall because the run length is fixed) and then always performs about log(n/8) rounds of merging, so it is O(n log n). It does not reproduce library Timsort features such as natural run detection, so it does not speed up on sorted input.
Source of facts: Complexity follows the learning guide's comparison table and text, and this app's implementation.
Trace on a small array
The first operations on the input [5, 2, 4, 1, 3, 8, 7, 6, 10, 9], following the same steps as the app.
| # | Operation | Array after |
|---|---|---|
| 1 | Swap [0]=5 and [1]=2 | [2, 5, 4, 1, 3, 8, 7, 6, 10, 9] |
| 2 | Swap [1]=5 and [2]=4 | [2, 4, 5, 1, 3, 8, 7, 6, 10, 9] |
| 3 | Swap [2]=5 and [3]=1 | [2, 4, 1, 5, 3, 8, 7, 6, 10, 9] |
| 4 | Swap [1]=4 and [2]=1 | [2, 1, 4, 5, 3, 8, 7, 6, 10, 9] |
| 5 | Swap [0]=2 and [1]=1 | [1, 2, 4, 5, 3, 8, 7, 6, 10, 9] |
| 6 | Swap [3]=5 and [4]=3 | [1, 2, 4, 3, 5, 8, 7, 6, 10, 9] |
| 7 | Swap [2]=4 and [3]=3 | [1, 2, 3, 4, 5, 8, 7, 6, 10, 9] |
| 8 | Swap [5]=8 and [6]=7 | [1, 2, 3, 4, 5, 7, 8, 6, 10, 9] |
…and so on. In this trace, 21 compare / swap / write operations in total produce [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].
Suitable inputs and caveats
- The two phases — small insertion sorts, then merging — are clearly visible.
- As the learning guide notes, it is a simplified version without natural run detection.
- Both insertion sort and merging keep equal values in order, so it is stable.
FAQ
Is this app's Tim sort the same as library Timsort?
No. It is a simplified version that insertion-sorts 8-element runs and then merges them; natural run detection and similar features are not reproduced.
Why start with insertion sort?
On short runs insertion sort's steps are simple. This app insertion-sorts 8-element runs and then switches to merging.