Timsort

hip-hop, educational · 2:43

Listen on 93

Lyrics

[Verse 1]
Started back in Python with a hybrid mind
Merge sort meets insertion, perfectly designed  
Tim Peters saw the patterns in the real world data
Sorted runs and galloping, made algorithms better
Binary insertion when the size is small
Merge the longer sequences, efficiency for all
Adaptive to the input, stable as can be
Natural runs ascending, that's the Timsort key

[Chorus]
Tim-sort, Tim-sort, hybrid is the way
Merge and insert together, stable sorting stays
Gallop mode when one run wins the race
Min-merge keeps the stack in perfect place
Tim-sort, Tim-sort, runs are what we find
Adaptive algorithm for the data that's designed

[Verse 2]
Scan the array forward, find the natural runs
Strictly descending flipped, ascending ones
Minimum run length calculated by the size
Extend with binary insertion, that's the compromise  
Stack maintains the runs until it's time to merge
Invariants keep balance as the process does converge
When one run keeps winning, galloping takes control
Double up the jump size, that's the searching goal

[Chorus]
Tim-sort, Tim-sort, hybrid is the way
Merge and insert together, stable sorting stays
Gallop mode when one run wins the race
Min-merge keeps the stack in perfect place
Tim-sort, Tim-sort, runs are what we find
Adaptive algorithm for the data that's designed

[Bridge]
Seven element threshold for insertion sort to shine
Merge sort handles bigger, crossing over the line
Stable means equal elements keep their original place
Linear time best case when data shows its grace
Worst case n log n, average case the same
But real world performance puts Timsort in the fame

[Verse 3]
Two finger merge technique with temporary space
Copy smaller run first, then merge into place
Gallop threshold seven, then it drops to zero
Exit when the wins fall below the counting hero
Merge collapse maintains three rules on the stack
Balance keeps efficiency, performance on track
From Python's standard library to Java's arrays
Timsort rules the sorting in these modern days

[Chorus]
Tim-sort, Tim-sort, hybrid is the way
Merge and insert together, stable sorting stays
Gallop mode when one run wins the race
Min-merge keeps the stack in perfect place
Tim-sort, Tim-sort, runs are what we find
Adaptive algorithm for the data that's designed

[Outro]
When your data's partially sorted, Timsort's your friend
Hybrid adaptation means efficiency to the end
Remember Tim Peters and his sorting innovation
Stable, fast, and smart for every application

← Counting sort | Binary search →