{"id":464,"date":"2025-06-29T20:08:29","date_gmt":"2025-06-29T14:38:29","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=464"},"modified":"2025-06-29T20:08:30","modified_gmt":"2025-06-29T14:38:30","slug":"recursive-insertion-sort","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/recursive-insertion-sort\/","title":{"rendered":"Recursive Insertion Sort in Python"},"content":{"rendered":"\n<p>You\u2019re asked to sort an array using <strong>Insertion Sort<\/strong>, but instead of the classic iterative two-loop approach, you must implement it <strong>recursively in Python<\/strong>.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/www.geeksforgeeks.org\/problems\/insertion-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>Insertion Sort works by building the sorted portion of the array one element at a time: each new key is inserted into its correct place among the already-sorted elements to its left.<\/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>[9, 5, 1, 4, 3]<\/code><\/td><td><code>[1, 3, 4, 5, 9]<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>The recursive version mimics the \u201cexpand-then-insert\u201d logic by sorting the first <code>n \u2013 1<\/code> elements recursively, then inserting the <code>n<\/code>-th element (<code>key<\/code>) into that sorted prefix.<\/p>\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-88b8596f-0f35-4d6b-8c96-4b52f585dce8\" 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-insertion-sort\/#0-recursive-insertion-sort-solution-\" style=\"\">Recursive Insertion Sort Solution \ud83d\udd02<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/recursive-insertion-sort\/#1-intuition-amp-approach\" style=\"\">Intuition &amp; Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/recursive-insertion-sort\/#2-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/recursive-insertion-sort\/#3-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/recursive-insertion-sort\/#4-dry-run-array-4-3-2-\" style=\"\">Dry Run (Array [4, 3, 2])<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/recursive-insertion-sort\/#5-time-amp-space-complexity\" style=\"\">Time &amp; Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/recursive-insertion-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-insertion-sort-solution-\">Recursive Insertion 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 inherently sorted; stop recursion.<\/li>\n\n\n\n<li><strong>Recursive Step<\/strong> \u2013 Recursively sort the prefix <code>arr[0 \u2026 n \u2013 2]<\/code>.<\/li>\n\n\n\n<li><strong>Insertion Phase<\/strong> \u2013 Treat <code>arr[n \u2013 1]<\/code> as <code>key<\/code>; shift larger elements in the sorted prefix one position to the right until you find the correct spot, then insert <code>key<\/code>.<\/li>\n\n\n\n<li>The recursion depth decreases by one each call, ultimately reaching the base case.<\/li>\n<\/ol>\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 func(self, arr, n):\n        # Base case: array of size 0 or 1 is already sorted\n        if n &lt;= 1:\n            return\n        \n        # Recursively sort the first n-1 elements\n        self.func(arr, n - 1)\n\n        # Insert arr[n-1] (the 'key') into the sorted prefix\n        key = arr[n - 1]      # element to place\n        j = n - 2             # start from the last index of the sorted prefix\n        \n        # Shift elements that are greater than 'key' to the right\n        while j &gt;= 0 and arr[j] &gt; key:\n            arr[j + 1] = arr[j]\n            j -= 1\n        \n        # Position found; insert the key\n        arr[j + 1] = key\n\n    def insertionSort(self, arr):\n        # function that kicks off recursion for the whole array\n        self.func(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\">func<\/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: array of size 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\"># Recursively sort the first n-1 elements<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.func(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: #6A9955\"># Insert arr[n-1] (the &#39;key&#39;) into the sorted prefix<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        key = arr[n - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">]      <\/span><span style=\"color: #6A9955\"># element to place<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        j = n - <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">             <\/span><span style=\"color: #6A9955\"># start from the last index of the sorted prefix<\/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\"># Shift elements that are greater than &#39;key&#39; to the right<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> j &gt;= <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> arr[j] &gt; key:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            arr[j + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">] = arr[j]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            j -= <\/span><span style=\"color: #B5CEA8\">1<\/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\"># Position found; insert the key<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        arr[j + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">] = key<\/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\">insertionSort<\/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\"># function that kicks off recursion for the whole array<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.func(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><code>self.func(arr, n \u2013 1)<\/code><\/strong> sorts the prefix by recursion before any insertion takes place.<\/li>\n\n\n\n<li><strong><code>while j >= 0 and arr[j] > key<\/code><\/strong> walks backward through the sorted prefix, shifting larger elements rightward to make space.<\/li>\n\n\n\n<li><strong><code>arr[j + 1] = key<\/code><\/strong> drops <code>key<\/code> into its rightful place, leaving <code>arr[0 \u2026 n \u2013 1]<\/code> fully sorted when the function returns.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-dry-run-array-4-3-2-\">Dry Run (Array <code>[4, 3, 2]<\/code>)<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Call Depth<\/th><th><code>n<\/code><\/th><th>Sorted Prefix After Recursion<\/th><th>Insertion Action<\/th><th>Array State After Return<\/th><\/tr><\/thead><tbody><tr><td>1<\/td><td>3<\/td><td><code>[3, 4]<\/code> sorted<\/td><td>Insert <code>2<\/code> \u2192 shift <code>4, 3<\/code><\/td><td><code>[2, 3, 4]<\/code><\/td><\/tr><tr><td>2<\/td><td>2<\/td><td><code>[4]<\/code> sorted<\/td><td>Insert <code>3<\/code> \u2192 shift <code>4<\/code><\/td><td><code>[3, 4, 2]<\/code> (before depth-1)<\/td><\/tr><tr><td>3 (base)<\/td><td>1<\/td><td>\u2014<\/td><td>\u2014<\/td><td><code>[4, 3, 2]<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Unwinding reconstructs the fully sorted array <code>[2, 3, 4]<\/code>.<\/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 Insertion Sort, because each insertion can shift up to <code>n<\/code> elements in the worst case.<\/li>\n\n\n\n<li><strong>Space:<\/strong> <code>O(n)<\/code> \u2013 recursion adds a stack frame per level (Python doesn\u2019t optimize tail calls).<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"6-conclusion\">Conclusion<\/h3>\n\n\n\n<p>Recursive Insertion Sort keeps the simplicity of its iterative counterpart while showcasing how <strong>\u201cprocess-a-prefix \u2192 insert-last\u201d<\/strong> can replace an outer loop. Though its quadratic time makes it unsuitable for very large inputs, it remains a valuable technique for learning recursion, algorithm design, and problem decomposition.<\/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\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>You\u2019re asked to sort an array using Insertion Sort, but instead of the classic iterative two-loop approach, you must implement it recursively in Python. Here&#8217;s the [Problem Link] to begin with. Insertion Sort works by building the sorted portion of the array one element at a time: each new key is inserted into its correct<\/p>\n","protected":false},"author":1,"featured_media":465,"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-464","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-insertion-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\/464","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=464"}],"version-history":[{"count":1,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/464\/revisions"}],"predecessor-version":[{"id":466,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/464\/revisions\/466"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/465"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=464"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=464"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=464"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}