{"id":299,"date":"2025-06-13T13:48:26","date_gmt":"2025-06-13T08:18:26","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=299"},"modified":"2025-07-07T20:07:56","modified_gmt":"2025-07-07T14:37:56","slug":"quick-sort-in-python","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/quick-sort-in-python\/","title":{"rendered":"Quick Sort Algorithm in Python | Explained"},"content":{"rendered":"\n<p><strong>Quick Sort<\/strong> is a popular sorting algorithm that follows a <strong>divide-and-conquer<\/strong> approach.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Choose a Pivot<\/strong>: Select one element of the array (in this code, the element at index low).<\/li>\n\n\n\n<li><strong>Partition<\/strong>: Arrange the array such that all elements <strong>less than or equal<\/strong> to the pivot lie to the pivot\u2019s left, and those <strong>greater<\/strong> than the pivot lie to its right.<\/li>\n\n\n\n<li><strong>Recursively<\/strong> sort the subarrays on both sides of the pivot.<\/li>\n<\/ol>\n\n\n\n<p>When implemented well, Quick Sort can be extremely efficient, often outperforming more stable algorithms like Merge Sort in practice, due to better cache performance. However, it does have a worst-case time complexity of <strong>O(n<\/strong><strong><sup>2<\/sup><\/strong><strong>)<\/strong> if the pivot selection is poor.<\/p>\n\n\n\n<p>So let&#8217;s get started with the [<strong><a href=\"https:\/\/www.geeksforgeeks.org\/problems\/quick-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>].<\/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-8b9124b1-7c38-4e17-baa1-a027ff6fbe7c\" 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\/quick-sort-in-python\/#0-1-understanding-the-code-\" style=\"\">1. Understanding the Code<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/quick-sort-in-python\/#1-how-the-partition-function-works-\" style=\"\">How the partition function works:<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/quick-sort-in-python\/#2-how-the-quick_sort-function-works-\" style=\"\">How the quick_sort function works:<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/quick-sort-in-python\/#3-2-example-step-by-step-dry-run-\" style=\"\">2. Example: Step-by-Step Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/quick-sort-in-python\/#4-3-time-complexity-\" style=\"\">3. Time Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/quick-sort-in-python\/#5-4-space-complexity-\" style=\"\">4. Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/quick-sort-in-python\/#6-5-key-takeaways-\" style=\"\">5. Key Takeaways<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"0-1-understanding-the-code-\"><strong>1. Understanding the Code<\/strong><\/h2>\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=\"def partition(self, arr, low, high):\n    pivot = arr[low]\n    i = low\n    j = high\n\n    while i &lt; j:\n        while i &lt;= high - 1 and arr[i] &lt;= pivot:\n            i += 1\n        while j &gt;= low + 1 and arr[j] &gt; pivot:\n            j -= 1\n        if i &lt; j:\n            arr[i], arr[j] = arr[j], arr[i]\n    \n    arr[low], arr[j] = arr[j], arr[low]\n    return j\" 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\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">partition<\/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\">low<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">high<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    pivot = arr[low]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    i = low<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    j = high<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> i &lt; j:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> i &lt;= high - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> arr[i] &lt;= pivot:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            i += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> j &gt;= low + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> arr[j] &gt; pivot:<\/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 style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> i &lt; j:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            arr[i], arr[j] = arr[j], arr[i]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    arr[low], arr[j] = arr[j], arr[low]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> j<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-how-the-partition-function-works-\"><strong>How the partition function works:<\/strong><\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Pivot Selection<\/strong>\n<ul class=\"wp-block-list\">\n<li>The first element in the current segment (arr[low]) is chosen as the pivot.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Initialize Pointers<\/strong>\n<ul class=\"wp-block-list\">\n<li>i starts from low.<\/li>\n\n\n\n<li>j starts from high.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Iterate until <\/strong><strong>i &lt; j<\/strong>\n<ul class=\"wp-block-list\">\n<li><strong>Move <\/strong><strong>i<\/strong><strong> right<\/strong> as long as arr[i] &lt;= pivot. This step stops when you find an element that is <strong>greater<\/strong> than the pivot.<\/li>\n\n\n\n<li><strong>Move <\/strong><strong>j<\/strong><strong> left<\/strong> as long as arr[j] &gt; pivot. This step stops when you find an element that is <strong>less than or equal<\/strong> to the pivot.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Swap<\/strong>\n<ul class=\"wp-block-list\">\n<li>If i &lt; j, swap arr[i] and arr[j]. This pushes the large element (found at i) to the right part of the array and brings the smaller element (found at j) into the left part.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Final Pivot Swap<\/strong>\n<ul class=\"wp-block-list\">\n<li>Once the while i &lt; j loop ends, j effectively points to the position where the pivot should be placed.<\/li>\n\n\n\n<li>Swap arr[low] and arr[j] so that the pivot moves to its correct sorted position.<\/li>\n\n\n\n<li>Return j (the new index of the pivot) to the calling function.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<p>By the end of partition, all elements <strong>to the left<\/strong> of arr[j] are <strong>less than or equal<\/strong> to the pivot, and all elements <strong>to the right<\/strong> of arr[j] are <strong>greater<\/strong> than the pivot.<\/p>\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=\"def quickSort(self, arr, low, high):\n    if low &lt; high:\n        # Partition the array and get the pivot index\n        p_index = self.partition(arr, low, high)\n        # Recursively sort elements before and after partition\n        self.quickSort(arr, low, p_index - 1)\n        self.quickSort(arr, p_index + 1, high)\" 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\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">quickSort<\/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\">low<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">high<\/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\"> low &lt; high:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Partition the array and get the pivot index<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        p_index = <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.partition(arr, low, high)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Recursively sort elements before and after partition<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.quickSort(arr, low, p_index - <\/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: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.quickSort(arr, p_index + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, high)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-how-the-quick_sort-function-works-\"><strong>How the <\/strong><strong>quick_sort<\/strong><strong> function works:<\/strong><\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Base Condition<\/strong>:\n<ul class=\"wp-block-list\">\n<li>If low &gt;= high, it means the segment of the array is of size 0 or 1, which is already sorted.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Partition and Recursion<\/strong>:\n<ul class=\"wp-block-list\">\n<li>Call partition(arr, low, high) to place the pivot in its correct position, and get that index as p_index.<\/li>\n\n\n\n<li>Recursively sort the two subarrays:\n<ul class=\"wp-block-list\">\n<li>Elements <strong>before<\/strong> the pivot: from low to p_index &#8211; 1.<\/li>\n\n\n\n<li>Elements <strong>after<\/strong> the pivot: from p_index + 1 to high.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-how-the-quick_sort-function-works-\">Whole Code All together<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro padding-bottom-disabled cbp-has-line-numbers\" 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;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);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    # Function to sort a list using quick sort algorithm.\n    def quickSort(self, arr, low, high):\n        if low &lt; high:\n            # Partition the array and get the pivot index\n            p_index = self.partition(arr, low, high)\n            # Recursively sort elements before and after partition\n            self.quickSort(arr, low, p_index - 1)\n            self.quickSort(arr, p_index + 1, high)\n\n    def partition(self, arr, low, high):\n        pivot = arr[low]\n        i = low\n        j = high\n\n        while i &lt; j:\n            while i &lt;= high - 1 and arr[i] &lt;= pivot:\n                i += 1\n            while j &gt;= low + 1 and arr[j] &gt; pivot:\n                j -= 1\n            if i &lt; j:\n                arr[i], arr[j] = arr[j], arr[i]\n\n        arr[low], arr[j] = arr[j], arr[low]\n        return j\" 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: #6A9955\"># Function to sort a list using quick sort algorithm.<\/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\">quickSort<\/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\">low<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">high<\/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\"> low &lt; high:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># Partition the array and get the pivot index<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            p_index = <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.partition(arr, low, high)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># Recursively sort elements before and after partition<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.quickSort(arr, low, p_index - <\/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: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.quickSort(arr, p_index + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, high)<\/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\">partition<\/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\">low<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">high<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        pivot = arr[low]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        i = low<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        j = high<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> i &lt; j:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> i &lt;= high - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> arr[i] &lt;= pivot:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                i += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> j &gt;= low + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> arr[j] &gt; pivot:<\/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 style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> i &lt; j:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                arr[i], arr[j] = arr[j], arr[i]<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        arr[low], arr[j] = arr[j], arr[low]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> j<\/span><\/span><\/code><\/pre><span style=\"display:flex;align-items:flex-end;padding:10px;width:100%;justify-content:flex-end;background-color:#1E1E1E;color:#c7c7c7;font-size:12px;line-height:1;position:relative\">Python<\/span><\/div>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><em>Also read about the Python Program to <strong><a href=\"https:\/\/codeanddebug.in\/blog\/merge-sort-algorithm-in-python\/\" data-type=\"post\" data-id=\"296\" 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;\">Implement Merge Sort Algorithm<\/span><\/mark><\/a><\/strong>.<\/em><\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"3-2-example-step-by-step-dry-run-\"><strong>2. Example: Step-by-Step Dry Run<\/strong><\/h2>\n\n\n\n<p>Given:<\/p>\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=\"arr = [64, 34, 25, 12, 22, 12, 12, 11, 90]\nquick_sort(arr, 0, len(arr) - 1)\nprint(f&quot;Sorted array = {arr}&quot;)\" 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: #D4D4D4\">arr = [<\/span><span style=\"color: #B5CEA8\">64<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">34<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">25<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">12<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">22<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">12<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">12<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">11<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">90<\/span><span style=\"color: #D4D4D4\">]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">quick_sort(arr, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(arr) - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #DCDCAA\">print<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #569CD6\">f<\/span><span style=\"color: #CE9178\">&quot;Sorted array = <\/span><span style=\"color: #569CD6\">{<\/span><span style=\"color: #D4D4D4\">arr<\/span><span style=\"color: #569CD6\">}<\/span><span style=\"color: #CE9178\">&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p><strong>Initial Call<\/strong>: quick_sort(arr, 0, 8) (since len(arr) &#8211; 1 = 8).<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>First Partition<\/strong>:\n<ul class=\"wp-block-list\">\n<li>low = 0, high = 8, pivot = arr[0] = 64.<\/li>\n\n\n\n<li>i = 0, j = 8.<\/li>\n\n\n\n<li>Move i right until arr[i] is &gt; pivot.<\/li>\n\n\n\n<li>Move j left until arr[j] is \u2264 pivot.<\/li>\n\n\n\n<li>Swap elements when i &lt; j.<\/li>\n\n\n\n<li>Eventually, swap the pivot into its correct position, returning the index of the pivot.<\/li>\n\n\n\n<li>After this partition, the pivot (64) sits in its final position, with all smaller or equal elements to its left and larger elements to its right.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Recursive Sort of Left and Right Segments<\/strong>:\n<ul class=\"wp-block-list\">\n<li>Left side: everything before pivot index.<\/li>\n\n\n\n<li>Right side: everything after pivot index.<\/li>\n\n\n\n<li>Each segment is similarly partitioned and sorted.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Final Sorted Array<\/strong>:\n<ul class=\"wp-block-list\">\n<li>After the recursion completes for all subparts, the entire list becomes sorted.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<p>In practice, because there are repeated elements like 12 and 12, the code ensures they all end up in the correct final positions relative to 64 and 90.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"4-3-time-complexity-\"><strong>3. Time Complexity<\/strong><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Best and Average Case<\/strong>: <strong><em>O(nlog\u2061n)<\/em><\/strong>. When the pivot divides the array into subarrays of nearly equal size, you get more balanced splits.<\/li>\n\n\n\n<li><strong>Worst Case<\/strong>: <strong>O(n<\/strong><strong><sup>2<\/sup><\/strong><strong>)<\/strong>. If the pivot is consistently chosen poorly (for example, the smallest or largest element in each partition), each partition results in extremely unbalanced subarrays.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5-4-space-complexity-\"><strong>4. Space Complexity<\/strong><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Quick Sort is generally considered an <strong>in-place<\/strong> sort since it rearranges the array in-place.<\/li>\n\n\n\n<li>Space complexity is <strong>O(log\u2061n)<\/strong> for the recursion call stack in the best\/average case. In the worst case, it can go up to <strong>O(n)<\/strong> because of the depth of the recursion tree.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6-5-key-takeaways-\"><strong>5. Key Takeaways<\/strong><\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Pivot Selection Matters<\/strong>: Different strategies for selecting the pivot (first element, last element, random pivot, median-of-three, etc.) can significantly influence performance.<\/li>\n\n\n\n<li><strong>In-Place Sort<\/strong>: Quick Sort does not need extra arrays (unlike Merge Sort), so memory usage can be lower in typical implementations.<\/li>\n\n\n\n<li><strong>Unstable<\/strong>: Quick Sort does not guarantee that identical elements remain in their original order.<\/li>\n<\/ol>\n\n\n\n<p><strong>Widely Used<\/strong>: Due to good average-case performance, it\u2019s often the default choice in many standard libraries (e.g., C++ STL\u2019s sort uses a variant of Quick Sort called introsort).<\/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\">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","protected":false},"excerpt":{"rendered":"<p>Quick Sort is a popular sorting algorithm that follows a divide-and-conquer approach. When implemented well, Quick Sort can be extremely efficient, often outperforming more stable algorithms like Merge Sort in practice, due to better cache performance. However, it does have a worst-case time complexity of O(n2) if the pivot selection is poor. So let&#8217;s get<\/p>\n","protected":false},"author":1,"featured_media":301,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ub_ctt_via":"","footnotes":""},"categories":[3,4],"tags":[12],"class_list":{"0":"post-299","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-sorting-algos"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/06\/quick-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\/299","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=299"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/299\/revisions"}],"predecessor-version":[{"id":553,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/299\/revisions\/553"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/301"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=299"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=299"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=299"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}