{"id":461,"date":"2025-06-29T20:01:24","date_gmt":"2025-06-29T14:31:24","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=461"},"modified":"2025-06-29T20:01:25","modified_gmt":"2025-06-29T14:31:25","slug":"recursive-bubble-sort","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/recursive-bubble-sort\/","title":{"rendered":"Recursive Bubble Sort in Python"},"content":{"rendered":"\n<p>You\u2019re given an unsorted array of integers and asked to <strong>sort it in non-decreasing order using Bubble Sort,  but implemented <em>recursively<\/em>, without any explicit loops<\/strong>.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/www.geeksforgeeks.org\/problems\/bubble-sort\/1\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n\n<p>Bubble Sort works by repeatedly \u201cbubbling\u201d the largest (or smallest) element to the end of the current segment through adjacent swaps. In its classic iterative form, this takes two nested loops. The challenge here is to reproduce the same behavior with a recursive function.<\/p>\n\n\n\n<p><strong>Example<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Input array<\/th><th>Output array<\/th><\/tr><\/thead><tbody><tr><td><code>[5, 1, 4, 2, 8]<\/code><\/td><td><code>[1, 2, 4, 5, 8]<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-9aa34069-5d70-44c3-b60a-cfe6b16d34d5\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"false\" data-initiallyshow=\"false\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/recursive-bubble-sort\/#0-recursive-bubble-sort-solution-\" style=\"\">Recursive Bubble Sort Solution \ud83d\udd04<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/recursive-bubble-sort\/#1-intuition-amp-approach\" style=\"\">Intuition &amp; Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/recursive-bubble-sort\/#2-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/recursive-bubble-sort\/#3-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/recursive-bubble-sort\/#4-dry-run-example-3-2-1-\" style=\"\">Dry Run (Example [3, 2, 1])<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/recursive-bubble-sort\/#5-time-amp-space-complexity\" style=\"\">Time &amp; Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/recursive-bubble-sort\/#6-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0-recursive-bubble-sort-solution-\">Recursive Bubble Sort Solution<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-intuition-amp-approach\">Intuition &amp; Approach<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Base Case<\/strong> \u2013 A segment of length <code>0<\/code> or <code>1<\/code> is already sorted; stop recursing.<\/li>\n\n\n\n<li><strong>Single Pass (Bubble Phase)<\/strong> \u2013 Sweep once through <code>arr[0 \u2026 n-1]<\/code>, swapping whenever the current element is larger than the next. After this pass, the <strong>largest element settles at index <code>n-1<\/code><\/strong>.<\/li>\n\n\n\n<li><strong>Recursive Call<\/strong> \u2013 The last position is now correct, so recursively sort the prefix <code>arr[0 \u2026 n-2]<\/code>.<\/li>\n\n\n\n<li>Repeat until the base case is reached.<\/li>\n<\/ol>\n\n\n\n<p>Each recursion level shrinks the effective problem size by 1, mimicking the outer loop of the iterative version.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def bubble_sort_recursive(self, arr, n):\n        # Base case \u2013 a segment of length 0 or 1 is already sorted\n        if n &lt;= 1:\n            return\n        \n        # One full &quot;bubble&quot; pass:\n        # After this loop, the largest element within arr[0 \u2026 n-1]\n        # will have moved to index n-1\n        for i in range(n - 1):\n            if arr[i] &gt; arr[i + 1]:\n                # Swap adjacent elements that are out of order\n                arr[i], arr[i + 1] = arr[i + 1], arr[i]\n        \n        # Recur on the array prefix arr[0 \u2026 n-2]\n        self.bubble_sort_recursive(arr, n - 1)\n\n    def bubbleSort(self, arr):\n        # Public wrapper that starts the recursion\n        self.bubble_sort_recursive(arr, len(arr))\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">bubble_sort_recursive<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">arr<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">n<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Base case \u2013 a segment of length 0 or 1 is already sorted<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> n &lt;= <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">return<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># One full &quot;bubble&quot; pass:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># After this loop, the largest element within arr[0 \u2026 n-1]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># will have moved to index n-1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> arr[i] &gt; arr[i + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># Swap adjacent elements that are out of order<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                arr[i], arr[i + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">] = arr[i + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">], arr[i]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Recur on the array prefix arr[0 \u2026 n-2]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.bubble_sort_recursive(arr, n - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">bubbleSort<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">arr<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Public wrapper that starts the recursion<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.bubble_sort_recursive(arr, <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(arr))<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>First Pass (for-loop)<\/strong> \u2014 plays the role of Bubble Sort\u2019s inner loop, pushing the maximum element to the end of the current range.<\/li>\n\n\n\n<li><strong>Recursive Call<\/strong> \u2014 replaces the outer loop: after fixing position <code>n-1<\/code>, it sorts the remaining <code>n-1<\/code> elements.<\/li>\n\n\n\n<li><strong>Termination<\/strong> \u2014 when <code>n<\/code> becomes <code>1<\/code> the function returns without further work.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-dry-run-example-3-2-1-\">Dry Run (Example <code>[3, 2, 1]<\/code>)<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Call Depth<\/th><th>Current <code>n<\/code><\/th><th>Array State After Bubble Pass<\/th><\/tr><\/thead><tbody><tr><td>1<\/td><td>3<\/td><td><code>[2, 1, 3]<\/code><\/td><\/tr><tr><td>2<\/td><td>2<\/td><td><code>[1, 2, 3]<\/code><\/td><\/tr><tr><td>3<\/td><td>1 (base)<\/td><td>\u2014<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>The recursion unwinds; no additional swaps are needed because each prefix is already sorted when control returns.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"5-time-amp-space-complexity\">Time &amp; Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time:<\/strong> <code>O(n\u00b2)<\/code> \u2013 identical to iterative Bubble Sort (worst-case and average-case).<\/li>\n\n\n\n<li><strong>Space:<\/strong> <code>O(n)<\/code> \u2013 due to recursion depth; each call adds a new frame to the call stack.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"6-conclusion\">Conclusion<\/h3>\n\n\n\n<p>Recursive Bubble Sort swaps the traditional nested-loop construct for <strong>recursion + a single loop<\/strong>, capturing the same \u201clargest-element-to-the-end\u201d behavior. While its time complexity remains quadratic (so it isn\u2019t recommended for large datasets), the technique is a great exercise in converting iterative logic into recursive form and deepening your understanding of how Bubble Sort works under the hood.<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/www.codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\">+91-9712928220<\/a>.<\/em><\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>You\u2019re given an unsorted array of integers and asked to sort it in non-decreasing order using Bubble Sort, but implemented recursively, without any explicit loops. Here&#8217;s the [Problem Link] to begin with. Bubble Sort works by repeatedly \u201cbubbling\u201d the largest (or smallest) element to the end of the current segment through adjacent swaps. In its<\/p>\n","protected":false},"author":1,"featured_media":462,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ub_ctt_via":"","footnotes":""},"categories":[3,4],"tags":[11,12],"class_list":{"0":"post-461","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-beginner","9":"tag-recursion","10":"tag-sorting-algos"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/06\/recursive-bubble-sort-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/461","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=461"}],"version-history":[{"count":1,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/461\/revisions"}],"predecessor-version":[{"id":463,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/461\/revisions\/463"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/462"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=461"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=461"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=461"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}