[Verse 1]
Started with insertion sort, simple but it's slow
Binary sort for the win when the data's gotta flow
But Python needed something that could handle every case
So Tim Peters stepped up, brought efficiency to the race
Hybrid algorithm mixing insertion with the merge
Small runs get insertion, big ones feel the urge
To split and then combine with that divide and conquer style
Galloping mode kicks in when patterns run for miles
[Chorus]
Tim-sort, Tim-sort, stable sorting king
Runs and merges, natural ordering
Small arrays insertion, large ones merge and split
Galloping when lopsided, that's the Timsort hit
Tim-sort, Tim-sort, adaptive to the core
Best case linear time, worst case n-log-n for sure
[Verse 2]
Start by finding runs, ascending or descending
If it's going down we flip it, keep the order trending
Minimum run size calculated from the length
Binary insertion sort gives small sections their strength
Stack of pending runs waiting for their turn to merge
When the invariants break, that's when we converge
Merge high and merge low, choosing the best path
Galloping mode engages when one side's doing the math
[Chorus]
Tim-sort, Tim-sort, stable sorting king
Runs and merges, natural ordering
Small arrays insertion, large ones merge and split
Galloping when lopsided, that's the Timsort hit
Tim-sort, Tim-sort, adaptive to the core
Best case linear time, worst case n-log-n for sure
[Bridge]
When the data's nearly sorted, Timsort's at its best
Recognizes patterns, puts efficiency to the test
Stable sort guarantee means equal elements stay
In their original order at the end of the day
Python's default sorting, Java uses it too
Real world performance, that's what it'll do
[Verse 3]
Galloping starts when one run wins seven straight
Binary search kicks in to calculate the fate
Copy to temporary space, merge back into place
Memory efficient algorithm running at full pace
Invariants maintained on that pending runs stack
When they're violated, merge operations attack
Sophisticated logic but the interface stays clean
Most powerful practical sort that you've ever seen
[Chorus]
Tim-sort, Tim-sort, stable sorting king
Runs and merges, natural ordering
Small arrays insertion, large ones merge and split
Galloping when lopsided, that's the Timsort hit
Tim-sort, Tim-sort, adaptive to the core
Best case linear time, worst case n-log-n for sure
[Outro]
From the mind of Tim Peters to production code today
Timsort revolutionized the sorting algorithm way
Hybrid approach mastery, real world data king
That's the Timsort legacy, let the sorted data sing