{"id":288,"date":"2026-11-13T12:37:03","date_gmt":"2026-11-13T04:37:03","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-timsort-merges-natural-runs\/"},"modified":"2026-11-13T21:58:36","modified_gmt":"2026-11-13T13:58:36","slug":"how-timsort-merges-natural-runs","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-timsort-merges-natural-runs\/","title":{"rendered":"How timsort merges natural runs"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Timsort<\/strong> finds runs that are already ordered, extends short ones with insertion sort, and merges them under a stack invariant that keeps the merge cost at <strong>O(n log n)<\/strong>. A strictly descending run is reversed so equal keys stay put, and the merge takes the left element on a tie, so the sort is <strong>stable<\/strong>. It is the sort behind Python&#8217;s <code>list.sort<\/code> and Java&#8217;s sort for objects.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Real arrays often contain ordered stretches: a sorted prefix, a reversed block, a run of equals. Mergesort of single items spends the same n log n on those stretches as on random data. A natural mergesort first consumes each stretch as a run, then merges runs. The remaining design problem is which pair to merge so that a long run is never merged, over and over, in a way that would ruin the bound.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Stability fixes two details. Only a strictly descending run is reversed, because reversing a non-increasing run would swap equal keys. The merge prefers the earlier run on a tie.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Every input is sorted stably in O(n log n) comparisons after the corrected collapse rule. A fully ordered input is recognized as one run and finishes in \u0398(n). Extra memory is proportional to n in the worst case, and smaller when runs are long, because a merge buffer can be sized to the shorter run. The minimum run length, minrun, is chosen in the range 32 through 64 so that the number of minruns in n is at or just below a power of two.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The stack invariant, with A the top run and B, C beneath it, is B &gt; A and C &gt; A+B. It exists so each merge charges to a doubling argument. A 2015 proof check showed the original collapse rule can break that invariant on a crafted pattern of run lengths. Current CPython and Java TimSort use a corrected collapse. Copying an old blog&#8217;s merge order copies the bug.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Scan for the next run. If it is strictly descending, reverse it. If its length is below minrun, extend it to minrun with insertion sort.<\/li>\n<li>Push the run on a stack. While the lengths violate B &gt; A or C &gt; A+B, merge the adjacent pair that the library&#8217;s collapse rule names.<\/li>\n<li>On a tie during a merge, take the element from the left run.<\/li>\n<li>If one run wins a run of comparisons, gallop: exponential search in the other run and copy a block. The threshold starts at 7 consecutive wins and then adapts.<\/li>\n<li>When the input ends, collapse the stack until one run remains.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">This is a stable adaptive comparison sort for random-access records. Fixed-width integers in a large array may still be faster under radix sort. An in-place unstable worst-case sort is introsort. The gallop is an optimization of the same merge, and turning it off still sorts.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when natural runs are merged in an arbitrary order<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Merge the two newest runs whenever two exist<\/td>\n<td>A pattern of run lengths can force a long run to be rewritten too often. The stack invariant is what blocks that pattern.<\/td>\n<\/tr>\n<tr>\n<td>Reverse every non-increasing run<\/td>\n<td>Equals inside a descending-or-equal stretch swap places. The sort becomes unstable.<\/td>\n<\/tr>\n<tr>\n<td>Copy a pre-2015 collapse rule verbatim<\/td>\n<td>That rule does not maintain the invariant used in the n log n proof. Current library code has a tighter collapse.<\/td>\n<\/tr>\n<tr>\n<td>Use timsort where a stable order is forbidden to allocate<\/td>\n<td>The merge buffer is part of the algorithm. A constant-space worst case is heapsort, and it will not be stable.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">A non-adaptive stable sort with a simpler proof is straight mergesort. An unstable in-place library sort for primitive keys is often a dual-pivot quicksort or introsort, which is a different contract.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">This Python fragment finds natural runs, reverses a strictly descending run so the sort stays stable, and merges while keeping the stack invariant that each lower run is longer than the run above it. It prints <code>1 2 3 4 5 6<\/code>.<\/p>\n\n<pre><code class=\"language-python\">def runs(a):\n    out, i, n = [], 0, len(a)\n    while i &lt; n:\n        j = i + 1\n        if j &lt; n and a[j] &lt; a[i]:\n            while j &lt; n and a[j] &lt; a[j - 1]:\n                j += 1\n            chunk = a[i:j]\n            chunk.reverse()\n        else:\n            while j &lt; n and a[j] &gt;= a[j - 1]:\n                j += 1\n            chunk = a[i:j]\n        out.append(chunk)\n        i = j\n    return out\n\ndef merge(left, right):\n    i = j = 0\n    out = []\n    while i &lt; len(left) and j &lt; len(right):\n        if left[i] &lt;= right[j]:\n            out.append(left[i]); i += 1\n        else:\n            out.append(right[j]); j += 1\n    return out + left[i:] + right[j:]\n\nstack = runs([3, 1, 2, 6, 5, 4])\nwhile len(stack) &gt; 1:\n    right = stack.pop()\n    left = stack.pop()\n    stack.append(merge(left, right))\nassert stack[0] == [1, 2, 3, 4, 5, 6]\nprint(*stack[0])\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\"><strong>Python <code>sorted<\/code><\/strong> and Java&#8217;s sort of objects are timsort: they find natural runs, give a short run an insertion-sort boost, and merge. The stable library sort is this algorithm. Introsort is the unstable in-place alternative in C++.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop timsort when stability is irrelevant and allocation is forbidden, or when the keys are machine words large enough for radix sort to win. Keep it for object arrays and any other stable sort where real inputs have runs, which is why the major language libraries use it there.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for timsort returns the stack invariant, the strict-descent rule, and the fact that the original collapse was wrong. <strong>Timsort is a stable natural mergesort whose n log n bound depends on a stack invariant the original collapse rule did not quite maintain.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: Timsort finds runs that are already ordered, extends short ones with insertion sort, and merges them under a stack invariant that keeps the merge cost at O(n log n). A strictly descending run is reversed so equal keys stay put, and the merge takes the left element&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,31],"tags":[],"class_list":["post-288","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-sorting"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/288","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=288"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/288\/revisions"}],"predecessor-version":[{"id":687,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/288\/revisions\/687"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=288"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=288"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=288"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}