{"id":161,"date":"2026-11-13T12:33:10","date_gmt":"2026-11-13T04:33:10","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-counting-sort-places-integers-from-a-histogram\/"},"modified":"2026-11-13T21:51:34","modified_gmt":"2026-11-13T13:51:34","slug":"how-counting-sort-places-integers-from-a-histogram","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-counting-sort-places-integers-from-a-histogram\/","title":{"rendered":"How counting sort places integers from a histogram"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Counting sort<\/strong> histograms keys that lie in 0, 1, \u2026, k\u22121, turns the histogram into prefix totals, and writes each record into the slot those totals name. The time and the extra memory are <strong>\u0398(n+k)<\/strong>. Writing from the end of the input and decrementing the total makes the sort <strong>stable<\/strong>. It is the digit sort inside radix sort, and it is a full sort whenever k is not much larger than n.<\/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\">Comparison sorting needs \u03a9(n log n) comparisons. Integer keys in a bounded range can be grouped by counting, which never compares two keys with each other. The histogram says how many keys belong in each bucket. A prefix sum of that histogram says the first output index that follows every copy of a given key.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Stability matters because radix sort calls this procedure once per digit and needs equal digits to keep the order established by the previous digit.<\/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\">One pass counts, one pass builds prefixes, one pass writes. That is \u0398(n+k) time. The count array has length k and the output array has length n. Keys outside 0..k\u22121 are a precondition failure, not a slower case. Negative keys are shifted by a constant only when a finite lower bound is known and k stays moderate.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The stable write scans the input from index n\u22121 down to 0. The prefix count[v] is the number of keys that are at most v, so the last input key with value v belongs at index count[v]\u22121. Decrementing count[v] leaves the previous copy of v one slot to the left. Equal keys therefore keep their input order.<\/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>Allocate a count array of length k, initially zero, and an output array of length n.<\/li>\n<li>For each key v, increment count[v].<\/li>\n<li>Replace count[v] with the sum of count[0] through count[v]. count[v] is now the number of keys that are \u2264 v.<\/li>\n<li>For i from n\u22121 down to 0, let v be the key at i. Write record i to output index count[v]\u22121, then decrement count[v].<\/li>\n<li>Copy the output back if the caller needs the result in the original array.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The linear bound holds when k is \u0398(n), or at least small enough that a length-k array is acceptable. A 64-bit key with k = 2^64 is a different problem. Radix sort then counts one digit, whose range is chosen to fit in memory.<\/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 keys are integers in 0..k\u22121<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Write the output from left to right<\/td>\n<td>The first copy of v takes the last slot reserved for v. Later equal keys land to its left, and the order of equals reverses.<\/td>\n<\/tr>\n<tr>\n<td>Allocate the histogram and skip the prefix sum<\/td>\n<td>A raw count says how many copies exist. The output index of a particular copy comes from the prefix total.<\/td>\n<\/tr>\n<tr>\n<td>Use it on arbitrary comparable objects<\/td>\n<td>The index into the histogram is the key itself. Objects that only support a comparison have no such index.<\/td>\n<\/tr>\n<tr>\n<td>Ignore k in the cost<\/td>\n<td>Time and memory both grow with the key domain. A sparse domain with a huge maximum is paid for in the count array, even if n is small.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">A comparison sort is the right tool for ordered objects with no integer rank. A digit-by-digit integer sort for large word sizes is radix sort, which calls this stable histogram once per digit.<\/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 counting-sort keys in 0\u20269. The write walks the input from the end, which is what keeps equal keys in their original order. Both print <code>1 2 2 4 4<\/code>.<\/p>\n\n<pre><code class=\"language-bash\">a=(4 2 2 1 4)\nn=${#a[@]}\ncount=()\nfor ((v=0; v&lt;10; v++)); do count[v]=0; done\nfor ((i=0; i&lt;n; i++)); do count[a[i]]=$((count[a[i]]+1)); done\nfor ((v=1; v&lt;10; v++)); do count[v]=$((count[v]+count[v-1])); done\nfor ((i=n-1; i&gt;=0; i--)); do\n  v=${a[i]}\n  count[v]=$((count[v]-1))\n  out[count[v]]=$v\ndone\necho &quot;${out[*]}&quot;\n<\/code><\/pre>\n<pre><code class=\"language-python\">def counting_sort(a, k=10):\n    count = [0] * k\n    for v in a:\n        count[v] += 1\n    for v in range(1, k):\n        count[v] += count[v - 1]\n    out = [0] * len(a)\n    for i in range(len(a) - 1, -1, -1):\n        v = a[i]\n        count[v] -= 1\n        out[count[v]] = v\n    return out\n\na = counting_sort([4, 2, 2, 1, 4])\nassert a == [1, 2, 2, 4, 4]\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\">Counting sort is the stable digit pass inside radix sort, and the histogram sort of a byte or a small integer key. Suffix-array construction uses those histograms. Comparison sorts are the fallback once the key is no longer a small integer.<\/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 counting sort when k is far larger than n and a length-k array will not fit, or when keys are not integers in a known range. Use radix sort for fixed-width integers and a comparison sort for general keys. Keep counting sort when the range is small, including as the stable inner sort of one radix digit.<\/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 counting sort returns the backward write that makes the histogram stable. <strong>Counting sort orders integer keys in 0..k\u22121 in \u0398(n+k) time, and scanning the input from the end is what keeps equal keys in their original 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: Counting sort histograms keys that lie in 0, 1, \u2026, k\u22121, turns the histogram into prefix totals, and writes each record into the slot those totals name. The time and the extra memory are \u0398(n+k). Writing from the end of the input and decrementing the total makes&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-161","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\/161","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=161"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/161\/revisions"}],"predecessor-version":[{"id":560,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/161\/revisions\/560"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=161"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=161"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=161"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}