{"id":175,"date":"2026-11-13T12:33:35","date_gmt":"2026-11-13T04:33:35","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-external-mergesort-sorts-beyond-memory\/"},"modified":"2026-11-13T21:51:50","modified_gmt":"2026-11-13T13:51:50","slug":"how-external-mergesort-sorts-beyond-memory","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-external-mergesort-sorts-beyond-memory\/","title":{"rendered":"How external mergesort sorts beyond memory"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>External mergesort<\/strong> sorts runs that fit in memory, writes them out, and merges them k at a time. With R runs and a k-way merge, the number of full passes over the file is <strong>\u2308log_k R\u2309<\/strong>. <strong>Replacement selection<\/strong> with a heap of M records produces runs whose expected length on random data is <strong>2M<\/strong>, which cuts R. The cost that matters is the volume of reads and writes, not the comparisons inside a run.<\/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\">The file does not fit in memory. A comparison sort that randomly seeks in the file thrashes. The access pattern that disks and sequential scans reward is: read a memory-sized chunk, sort it, write a run, then merge several runs by always emitting the smallest current head. Each merge pass reads every record once and writes every record once.<\/p>\n\n\n<p class=\"wp-block-paragraph\">How large a run the first phase can make determines how many merge passes follow. Filling a buffer and sorting it yields runs of length M. A heap that holds M records can do better on data that is not adversarial.<\/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\">Forming runs of length M from a file of N records produces R = \u2308N\/M\u2309 runs and uses one read and one write of the file. A k-way merge, limited by how many run heads fit in memory or how many streams the device can usefully read, reduces the run count by a factor k per pass. The pass count after the initial runs is \u2308log_k R\u2309. Total I\/O volume is about 2N times one plus that pass count, in units of records, plus bookkeeping.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Replacement selection keeps a min-heap of size M. The next input record joins the current run when it is at least the last record emitted, and otherwise waits in the heap for the next run. On random input the average run grows to about 2M, so R is about half of N\/M. The merge of those runs is unchanged. A polyphase merge redistributes runs across fewer tapes by Fibonacci counts when the number of streams is the binding constraint.<\/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>Choose M from the memory budget and k from the number of sequential streams that can be read together while an output stream is written.<\/li>\n<li>Either sort successive buffers of M records into runs, or run replacement selection so that a new record extends the current run when it is \u2265 the last output.<\/li>\n<li>Write the runs to external storage.<\/li>\n<li>Merge k runs at a time with a heap of the k current heads. Write one output run per merge. A head that is exhausted advances to the next record of that input run.<\/li>\n<li>Repeat the merge level until one run remains. That run is the sorted file.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The figure of merit is passes over external storage. An in-memory timsort or quicksort is the sort used inside a run, and it is not a substitute for the merge when N exceeds M. Replacement selection&#8217;s 2M expectation is for random records. Sorted input produces even longer runs. Adversarial input can hold the run length near M.<\/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 the file is larger than memory<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Sort through a memory-mapped file with quicksort<\/td>\n<td>The partition&#8217;s access pattern is not sequential. The device spends the time seeking, and the in-memory n log n formula no longer describes the cost.<\/td>\n<\/tr>\n<tr>\n<td>A 2-way merge when k streams fit<\/td>\n<td>The result is correct and the pass count is log\u2082 R instead of log_k R. Each extra pass reads and writes the whole file.<\/td>\n<\/tr>\n<tr>\n<td>Assume every run has length 2M<\/td>\n<td>That length is an expectation under replacement selection on random data. The planner should count the runs actually written.<\/td>\n<\/tr>\n<tr>\n<td>Merge without a heap, rescanning all k heads naively and ignoring I\/O<\/td>\n<td>CPU time is minor next to a pass. The failure that matters is an extra pass, not the log k inside the heap.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">In-memory sorting belongs to whichever comparison or radix sort fits the keys. External mergesort calls that algorithm only inside the run-formation buffer.<\/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 sorts memory-sized runs, writes them as the stand-in for external runs, and merges the run heads with a heap. Eight keys with a run length of 3 come back as <code>1 2 3 4 5 6 7 8<\/code>.<\/p>\n\n<pre><code class=\"language-python\">import heapq\ndata = [5, 1, 4, 2, 8, 3, 7, 6]\nrun_length = 3\nruns = [sorted(data[i:i + run_length]) for i in range(0, len(data), run_length)]\nheads = [(run[0], r, 0) for r, run in enumerate(runs)]\nheapq.heapify(heads)\nmerged = []\nwhile heads:\n    value, r, i = heapq.heappop(heads)\n    merged.append(value)\n    if i + 1 &lt; len(runs[r]):\n        heapq.heappush(heads, (runs[r][i + 1], r, i + 1))\nassert merged == sorted(data)\nprint(*merged)\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\">External mergesort is how a database sorts an <code>ORDER BY<\/code> that does not fit in memory, and how GNU <code>sort<\/code> handles a large file. Sorted runs are written out and merged. An in-memory timsort is what builds one run, not what merges the runs.<\/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 external mergesort when the file fits in memory with room for the sort&#8217;s own buffer. An in-memory sort then finishes with no extra pass. Keep it when N is larger than M, and spend the memory on longer runs and a wider k before spending it on a fancier in-memory sort.<\/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 external mergesort returns the pass count log_k of the number of runs, and the 2M runs from replacement selection. <strong>External mergesort sorts memory-sized runs and merges them k at a time, so the I\/O cost is a logarithmic number of sequential passes over the file.<\/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: External mergesort sorts runs that fit in memory, writes them out, and merges them k at a time. With R runs and a k-way merge, the number of full passes over the file is \u2308log_k R\u2309. Replacement selection with a heap of M records produces runs whose&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-175","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\/175","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=175"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/175\/revisions"}],"predecessor-version":[{"id":574,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/175\/revisions\/574"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=175"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=175"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=175"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}