Timsort is a hybrid sorting algorithm combining merge sort and insertion sort, designed to exploit existing order in real-world data. The article walks through how Timsort divides input into 'runs', sorts each with insertion sort, then merges them. Key optimizations include: detecting and reversing descending runs before sorting, galloping mode (bulk-adding consecutive elements during merging when one run dominates), adaptive merging that balances run sizes, and falling back to pure insertion sort for small inputs. Timsort achieves O(n) best-case on nearly-sorted data and O(n log n) average/worst-case, outperforming quicksort on partially sorted real-world data. It is the default sorting algorithm in Python, Java, and Rust. A simplified JavaScript implementation is provided via GitHub.

17m read timeFrom newsletter.systemdesign.one
Post cover image
Table of contents
IntroductionWhat is Timsort?WalkthroughOptimizationsPerformance CharacteristicsThe CodeConclusion

Sort: