{"id":162,"date":"2026-11-13T12:33:12","date_gmt":"2026-11-13T04:33:12","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-cycle-sort-writes-each-item-to-its-final-index\/"},"modified":"2026-11-13T21:51:35","modified_gmt":"2026-11-13T13:51:35","slug":"how-cycle-sort-writes-each-item-to-its-final-index","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-cycle-sort-writes-each-item-to-its-final-index\/","title":{"rendered":"How cycle sort writes each item to its final index"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Cycle sort<\/strong> follows the cycle that a permutation forms and writes each misplaced item directly to the index its rank names. Items already in place are left untouched. The comparison count stays <strong>\u0398(n\u00b2)<\/strong>, because each rank is computed by scanning. The point of the algorithm is the write pattern: a destination is written when an item arrives there, which is as few data writes as a cycle decomposition allows.<\/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\">Selection sort also hunts for the item that belongs in the next slot, and it does so with about n swaps. Inside one swap, the item that was sitting in that slot is thrown somewhere it may not belong, and a later pass must move it again. A permutation is a set of cycles. Rotating a cycle sends every member to its final index in a single trip.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The rank of an item is the number of items that must stand strictly before it. Computing that rank from scratch is a scan. The writes become cheap and the comparisons do not.<\/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 item either already sits at its final index or is written there during the rotation of its cycle. A cycle of length L is resolved by holding one item in a register and writing each following item into the hole, which is L writes of records into their destinations. Fixed points are not written. Extra memory is the register and a few indices. Time is \u0398(n\u00b2) comparisons in every case, because each cycle start scans the suffix to recompute ranks.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Duplicates need an explicit skip: if several items share a key, the first free index at that rank is the one that is still holding a different key. The standard treatment of duplicates is unstable. A write-minimal stable sort is a different, heavier construction.<\/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>For cycle_start from 0 to n\u22122, take the item at that index as the start of a cycle.<\/li>\n<li>Count how many items in the whole array belong strictly before it. That count is its destination.<\/li>\n<li>If the destination equals cycle_start, the item is a fixed point. Continue.<\/li>\n<li>If the destination already holds an equal key, advance to the next duplicate&#8217;s slot so a finished equal is left alone.<\/li>\n<li>Write the held item into the destination and pick up whatever was there. Recompute that new item&#8217;s rank the same way. Stop the cycle when the write returns to cycle_start.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The quadratic scans are the cost of discovering ranks with comparisons alone. When keys are integers in a small range, counting sort writes each record once into an output buffer in linear time and does not need this cycle walk. Cycle sort is what remains when the only legal mutation is a write into the same array and the number of those writes must stay minimal.<\/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 each item may be written only to its final slot<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Selection sort<\/td>\n<td>The displaced item is swapped into the minimum&#8217;s old slot, which is rarely its own destination. Later passes write it again.<\/td>\n<\/tr>\n<tr>\n<td>A cycle walk that does not recompute ranks after duplicates<\/td>\n<td>Two equal keys claim one index. The second write lands on a finished item or leaves a hole.<\/td>\n<\/tr>\n<tr>\n<td>Treat the write bound as a time bound<\/td>\n<td>Rank finding scans the array. Time stays quadratic on every input, including a sorted one, unless fixed points are detected and the scan is still paid by the items that move.<\/td>\n<\/tr>\n<tr>\n<td>Expect stability<\/td>\n<td>Items of equal key are assigned destinations by the order the scans discover them. That assignment does not preserve input order.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">Few writes into a separate output array, with linear time, belong to counting sort when the key range allows it. A general comparison sort that is willing to write \u0398(n log n) times belongs to heapsort.<\/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 cycle-sort. Each misplaced item is written to the index where it belongs. Both print <code>1 2 3 4 8 9<\/code>.<\/p>\n\n<pre><code class=\"language-bash\">a=(4 2 3 1 8 9)\nn=${#a[@]}\nfor ((start=0; start&lt;n-1; start++)); do\n  item=${a[start]}\n  pos=$start\n  for ((i=start+1; i&lt;n; i++)); do\n    if (( a[i] &lt; item )); then pos=$((pos+1)); fi\n  done\n  if (( pos == start )); then continue; fi\n  while (( a[pos] == item )); do pos=$((pos+1)); done\n  t=${a[pos]}; a[pos]=$item; item=$t\n  while (( pos != start )); do\n    pos=$start\n    for ((i=start+1; i&lt;n; i++)); do\n      if (( a[i] &lt; item )); then pos=$((pos+1)); fi\n    done\n    while (( a[pos] == item )); do pos=$((pos+1)); done\n    t=${a[pos]}; a[pos]=$item; item=$t\n  done\ndone\necho &quot;${a[*]}&quot;\n<\/code><\/pre>\n<pre><code class=\"language-python\">def cycle_sort(a):\n    a = a[:]\n    for start in range(len(a) - 1):\n        item = a[start]\n        pos = start + sum(1 for i in range(start + 1, len(a)) if a[i] &lt; item)\n        if pos == start:\n            continue\n        while a[pos] == item:\n            pos += 1\n        a[pos], item = item, a[pos]\n        while pos != start:\n            pos = start + sum(1 for i in range(start + 1, len(a)) if a[i] &lt; item)\n            while a[pos] == item:\n                pos += 1\n            a[pos], item = item, a[pos]\n    return a\n\nout = cycle_sort([4, 2, 3, 1, 8, 9])\nassert out == [1, 2, 3, 4, 8, 9]\nprint(*out)\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\">Cycle sort writes each item directly to its final index, which is the point when a write is expensive, as on an EEPROM or a flash page. The number of writes is optimal. A library sort that may rewrite an item several times is the wrong tool for that memory.<\/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 cycle sort when CPU time matters more than writes. Almost any n log n sort is faster. Keep it when each write to the data array is the scarce resource and a quadratic number of comparisons is acceptable, which includes some teaching cases and some write-limited memories.<\/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 cycle sort returns the cycle write pattern and the quadratic rank scans as two different costs. <strong>Cycle sort writes each misplaced item to the index its rank names, and it spends a quadratic number of comparisons to discover those ranks.<\/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: Cycle sort follows the cycle that a permutation forms and writes each misplaced item directly to the index its rank names. Items already in place are left untouched. The comparison count stays \u0398(n\u00b2), because each rank is computed by scanning. The point of the algorithm is 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-162","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\/162","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=162"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/162\/revisions"}],"predecessor-version":[{"id":561,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/162\/revisions\/561"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=162"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=162"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=162"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}