{"id":153,"date":"2026-11-13T12:32:54","date_gmt":"2026-11-13T04:32:54","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-bubble-sort-finishes-one-suffix-item-per-pass\/"},"modified":"2026-11-13T21:51:24","modified_gmt":"2026-11-13T13:51:24","slug":"how-bubble-sort-finishes-one-suffix-item-per-pass","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-bubble-sort-finishes-one-suffix-item-per-pass\/","title":{"rendered":"How bubble sort finishes one suffix item per pass"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Bubble sort<\/strong> swaps every adjacent inversion and then shortens the unsorted prefix. After pass i the last i items are in their final places. A pass that swaps nothing means the prefix is sorted too, so the scan stops. The worst case remains <strong>\u0398(n\u00b2)<\/strong> comparisons. It is a stable in-place sort for a short list, and a demonstration of how slowly adjacent swaps remove inversions.<\/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 input is a sequence under a total order. An adjacent swap fixes one neighboring inversion and can move an item only one slot closer to its destination. The useful question is which prefix is still unknown after each pass, and which observation proves that the unknown prefix has shrunk to nothing.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Stability means equal keys keep their original order. That holds when the comparison that swaps is strict: a lesser neighbor is swapped, and an equal neighbor is left where it is.<\/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\">Pass i bubbles the maximum of the still-unsorted prefix into index n\u22121\u2212i. Those finished suffix items are never touched again. If a full pass performs no swap, the prefix has no adjacent inversion. A total order with no adjacent inversion is sorted, so the early exit is exact. Extra memory is a handful of indices.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The best case, an array that is already sorted, is \u0398(n): one pass, zero swaps. The worst case, a reversed array, is \u0398(n\u00b2) comparisons and \u0398(n\u00b2) swaps. The average over random permutations is also \u0398(n\u00b2), because a random permutation has \u0398(n\u00b2) inversions and each swap removes only one.<\/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>Set the unsorted length to n.<\/li>\n<li>Scan adjacent pairs inside that length. A pair out of order is swapped, and the pass is marked dirty.<\/li>\n<li>If the pass was clean, return. The array is sorted.<\/li>\n<li>Otherwise decrease the unsorted length by one. The item that reached the end of the scan stays there.<\/li>\n<li>Repeat until the unsorted length is 1.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The accounting is for a comparison sort that may examine every adjacent pair. A nearly sorted file whose disorder is a few long-range swaps still pays a quadratic scan. Algorithms that move an item farther than one slot in one step are a different family.<\/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 adjacent swaps are the only move<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>One forward pass<\/td>\n<td>Each item moves at most one slot left. A minimum parked at the last index needs n\u22121 passes to reach the front.<\/td>\n<\/tr>\n<tr>\n<td>A fixed cap on the number of passes<\/td>\n<td>The inversion count depends on the input. A cap chosen in advance leaves a long inversion untouched.<\/td>\n<\/tr>\n<tr>\n<td>Swap when the comparison is greater-or-equal<\/td>\n<td>Equal keys change order. The sort stops being stable.<\/td>\n<\/tr>\n<tr>\n<td>Quote the best-case linear scan as the cost<\/td>\n<td>That scan is the already-sorted input. A random permutation still has \u0398(n\u00b2) inversions.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">Adjacent swaps are the right picture when the goal is to count inversions one by one. A sort that has to scale uses a merge, a heap, or a hybrid such as timsort or introsort.<\/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 bubble-sort the same integers. Each pass fixes one more suffix item. Both print <code>1 2 2 3 4<\/code>.<\/p>\n\n<pre><code class=\"language-bash\">a=(4 2 2 3 1)\nn=${#a[@]}\nfor ((i=0; i&lt;n-1; i++)); do\n  for ((j=0; j&lt;n-1-i; j++)); do\n    if (( a[j] &gt; a[j+1] )); then\n      t=${a[j]}\n      a[j]=${a[j+1]}\n      a[j+1]=$t\n    fi\n  done\ndone\necho &quot;${a[*]}&quot;\n<\/code><\/pre>\n<pre><code class=\"language-python\">a = [4, 2, 2, 3, 1]\nn = len(a)\nfor i in range(n - 1):\n    for j in range(n - 1 - i):\n        if a[j] &gt; a[j + 1]:\n            a[j], a[j + 1] = a[j + 1], a[j]\nassert a == sorted(a)\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\">Bubble sort is not the sort in any current standard library. The one idea that survives is the early exit when a pass swaps nothing, and only on a tiny nearly sorted array. <strong>Timsort<\/strong> and <strong>introsort<\/strong> are what languages actually call.<\/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 bubble sort once n leaves the range where a quadratic term is invisible, and whenever the input is not already almost ordered. Insertion sort has the same worst case, a better constant, and the same early exit on sorted data, and it is the usual small-array base case. Keep bubble sort when a stable adjacent-swap procedure is wanted and each pass must leave a finished, ordered suffix.<\/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 bubble sort returns the finished suffix, the swap-free exit, and the quadratic cost that still applies to a random permutation. <strong>Bubble sort places one suffix item per pass and may stop after a clean pass, and a random input still costs a quadratic number of adjacent swaps.<\/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: Bubble sort swaps every adjacent inversion and then shortens the unsorted prefix. After pass i the last i items are in their final places. A pass that swaps nothing means the prefix is sorted too, so the scan stops. The worst case remains \u0398(n\u00b2) comparisons. It is&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-153","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\/153","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=153"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/153\/revisions"}],"predecessor-version":[{"id":552,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/153\/revisions\/552"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=153"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=153"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=153"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}