{"id":243,"date":"2026-11-13T12:35:41","date_gmt":"2026-11-13T04:35:41","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-radix-sort-orders-keys-one-digit-at-a-time\/"},"modified":"2026-11-13T21:53:32","modified_gmt":"2026-11-13T13:53:32","slug":"how-radix-sort-orders-keys-one-digit-at-a-time","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-radix-sort-orders-keys-one-digit-at-a-time\/","title":{"rendered":"How radix sort orders keys one digit at a time"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>LSD radix sort<\/strong> stable-sorts fixed-width keys from the least significant digit to the most significant. Each digit is a counting sort on a radix-r alphabet. With d digits the time is <strong>\u0398(d(n+r))<\/strong>. Sorting the least significant digit first is what makes a later digit pass keep the order of the earlier ones. <strong>MSD radix sort<\/strong> starts at the high digit and recurses, which fits variable-length strings.<\/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\">A machine word or a fixed-length string is a sequence of digits. If the digits are sorted from low to high by a stable sort, then after the highest digit is processed the keys stand in numeric order. A high digit decides the coarse order. A low digit decides the order inside one high digit, and the stable pass has already established that finer order.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The radix r is a free parameter. A byte digit uses r = 256 and d = 4 on a 32-bit word, or d = 8 on a 64-bit word. A wider digit shrinks d and grows the histogram.<\/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\">For nonnegative fixed-width keys, d passes of a stable counting sort produce a stable sort of the whole key. Time is \u0398(d(n+r)) and extra memory is \u0398(n+r). That is linear in n whenever d and r are treated as constants, which they are for a machine word and a byte digit. Signed integers need the sign bit mapped so that negative values sort before nonnegative ones, usually by flipping the sign bit and then running the unsigned procedure.<\/p>\n\n\n<p class=\"wp-block-paragraph\">MSD radix sort partitions on the highest digit and recurses inside buckets whose digit matched. It can stop early on a bucket of length one, and it is the usual form for strings that do not share a common length. LSD is the usual form for integers, because every key has the same d and the passes are tight loops.<\/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 a radix r = 2^b. A byte, b = 8 and r = 256, is the common choice for word-sized keys.<\/li>\n<li>For each digit position from least significant to most significant, run a stable counting sort on that digit.<\/li>\n<li>The counting sort reads digit (key &gt;&gt; shift) &amp; (r\u22121), histograms r buckets, and writes records from the end of the current order.<\/li>\n<li>Increase the shift by b and repeat until the word is consumed.<\/li>\n<li>For signed integers, transform the sign bit so the unsigned digit order matches signed numeric order, then invert the transform if the bits must be restored. The sort itself only sees the transformed keys.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The procedure sorts keys that decompose into digits. It does not compare arbitrary objects, and it does not improve on comparison sorting when the key is a general string of unbounded length unless the MSD form is used and long shared prefixes are handled with care. Stability of the digit sort is a requirement, not an option.<\/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 a later digit pass must keep earlier order<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Sort the most significant digit first with a full-array LSD schedule<\/td>\n<td>A later low-digit pass then reorders keys that a high digit had already separated, unless each pass is confined to one high-digit bucket. That confined schedule is MSD radix sort.<\/td>\n<\/tr>\n<tr>\n<td>Use an unstable sort for the digit<\/td>\n<td>Equal digits lose the order computed by the less significant digits. The final order is then wrong inside those ties.<\/td>\n<\/tr>\n<tr>\n<td>Pick r = 2 and call the cost the same as r = 256<\/td>\n<td>Time is \u0398(d(n+r)) with d = word length in bits divided by log\u2082 r. The product d(n+r) actually changes with the radix.<\/td>\n<\/tr>\n<tr>\n<td>Run the unsigned passes on two&#8217;s-complement bits unchanged<\/td>\n<td>The sign bit makes negative numbers look larger than positive ones. They sort to the wrong end.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">A single small integer range uses counting sort with no digit loop. Comparison sorting is what remains for keys that have no digit decomposition.<\/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\">The Bash script and the Python script radix-sort nonnegative integers one decimal digit at a time, low digit first, with a stable counting pass per digit. Both print <code>2 24 45 66 75 90 170 802<\/code>.<\/p>\n\n<pre><code class=\"language-bash\">a=(170 45 75 90 802 24 2 66)\nn=${#a[@]}\nexp=1\nmax=${a[0]}\nfor v in &quot;${a[@]}&quot;; do if (( v &gt; max )); then max=$v; fi; done\nwhile (( max \/ exp &gt; 0 )); do\n  for ((d=0; d&lt;10; d++)); do count[d]=0; done\n  for ((i=0; i&lt;n; i++)); do\n    d=$(( (a[i] \/ exp) % 10 ))\n    count[d]=$((count[d]+1))\n  done\n  for ((d=1; d&lt;10; d++)); do count[d]=$((count[d]+count[d-1])); done\n  for ((i=n-1; i&gt;=0; i--)); do\n    d=$(( (a[i] \/ exp) % 10 ))\n    count[d]=$((count[d]-1))\n    out[count[d]]=${a[i]}\n  done\n  for ((i=0; i&lt;n; i++)); do a[i]=${out[i]}; done\n  exp=$((exp*10))\ndone\necho &quot;${a[*]}&quot;\n<\/code><\/pre>\n<pre><code class=\"language-python\">def counting_by_digit(a, exp):\n    count = [0] * 10\n    for v in a:\n        count[(v \/\/ exp) % 10] += 1\n    for d in range(1, 10):\n        count[d] += count[d - 1]\n    out = [0] * len(a)\n    for i in range(len(a) - 1, -1, -1):\n        d = (a[i] \/\/ exp) % 10\n        count[d] -= 1\n        out[count[d]] = a[i]\n    return out\n\ndef radix_sort(a):\n    exp = 1\n    while max(a) \/\/ exp:\n        a = counting_by_digit(a, exp)\n        exp *= 10\n    return a\n\na = radix_sort([170, 45, 75, 90, 802, 24, 2, 66])\nassert a == sorted([170, 45, 75, 90, 802, 24, 2, 66])\nprint(*a)\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\">Radix sort orders fixed-length integers and strings one digit at a time, and the counting pass inside suffix-array construction is the same idea. Historical punched-card sorters were radix sorts. Comparison sorts take over when the key does not split into digits.<\/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 LSD radix sort for variable-length strings, where MSD recursion avoids padding every string to the longest length. Drop it when n is small enough that a well-tuned comparison sort wins on constants. Keep it for large arrays of fixed-width integers, with a stable counting sort on each digit from low to high.<\/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 radix sort returns the low-to-high digit order and the reason the inner sort has to be stable. <strong>LSD radix sort stably sorts digits from low to high in \u0398(d(n+r)) time, and that order is what makes the last pass agree with numeric order.<\/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: LSD radix sort stable-sorts fixed-width keys from the least significant digit to the most significant. Each digit is a counting sort on a radix-r alphabet. With d digits the time is \u0398(d(n+r)). Sorting the least significant digit first is what makes a later digit pass keep the&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-243","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\/243","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=243"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/243\/revisions"}],"predecessor-version":[{"id":642,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/243\/revisions\/642"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=243"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=243"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=243"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}