{"id":9751,"date":"2020-10-22T16:49:06","date_gmt":"2020-10-22T16:49:06","guid":{"rendered":"https:\/\/www.askpython.com\/?p=9751"},"modified":"2023-02-16T19:56:59","modified_gmt":"2023-02-16T19:56:59","slug":"quicksort-algorithm","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/examples\/quicksort-algorithm","title":{"rendered":"How to Implement QuickSort in Python?"},"content":{"rendered":"\n<p>Quicksort is a <a href=\"https:\/\/www.askpython.com\/python\/array\/sort-array-python\" class=\"rank-math-link\">sorting algorithm<\/a> that follows the policy of <strong>divide and conquer.<\/strong> It works on the concept of choosing a pivot element and then arranging elements around the pivot by performing swaps. It recursively repeats this process until the array is sorted.<\/p>\n\n\n\n<p>In this tutorial we will learn how QuickSort works and how to write python code for its implementation. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Understanding the QuickSort Algorithm <\/h2>\n\n\n\n<p>The first step while performing Quicksort on an array is choosing a pivot element. There are various ways of choosing a pivot element. <\/p>\n\n\n\n<p>You can either select a <strong>random element<\/strong> or you can select the <strong>median of the array.<\/strong> For simplicity, we will be picking the <strong>first element of the <a href=\"https:\/\/www.askpython.com\/python\/array\/python-array-declaration\" class=\"rank-math-link\">array<\/a> as our pivot<\/strong> element.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1. Selecting a Pivot element<\/h3>\n\n\n\n<p>As discussed above, the first element is picked as the pivot element. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\npivot = array&#x5B;start]\n<\/pre><\/div>\n\n\n<p>After selecting a pivot element, we need to rearrange the elements around it. We rearrange the elements in such a way that all the elements smaller than the pivot are on the left and all the elements greater than the pivot are on the right. <\/p>\n\n\n\n<p><strong>How do we do this?<\/strong><\/p>\n\n\n\n<p> Let&#8217;s discuss that next. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2. Rearranging elements around Pivot <\/h3>\n\n\n\n<p>To rearrange the elements around the pivot we initialize two variables. <\/p>\n\n\n\n<p>Let&#8217;s call these variables <strong>low and high. <\/strong><\/p>\n\n\n\n<p>We initialize low with the second element of the array (one after the pivot) and high with the last element. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n low = start + 1\n high = end\n<\/pre><\/div>\n\n\n<p>To rearrange the elements we <strong>move the low towards the right and high towards the left<\/strong>. While doing this our motive is to make sure that all the values greater than the pivot should move towards the right and all the values smaller than the pivot should move towards the left. <\/p>\n\n\n\n<p>When we arrange the values in such a manner, we can find out the final position of the pivot element in the sorted array since all the elements smaller than the pivot are on its left and all the elements on the right are greater. <\/p>\n\n\n\n<p>Elements on right and left of the pivot may or may not be arranged in a sorted manner. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3. How to move low and high?<\/h3>\n\n\n\n<p>We move high towards left until high points towards a value smaller than pivot or until high is less than low. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nwhile low &lt;= high and array&#x5B;high] &gt;= pivot:\n     high = high - 1\n<\/pre><\/div>\n\n\n<p>Similarly, we move low towards the right until it points to a value that is higher than the pivot or until high is less than low. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nwhile low &lt;= high and array&#x5B;low] &lt;= pivot:\n     low = low + 1\n<\/pre><\/div>\n\n\n<p>After coming out of the loop, we check whether low is less than or equal to high. If that&#8217;s the case then we need to swap the values at high and low. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n if low &lt;= high:\n     array&#x5B;low], array&#x5B;high] = array&#x5B;high], array&#x5B;low]\n         \n<\/pre><\/div>\n\n\n<p>If low is greater than high we break out of the loop and return high as the position of pivot element. This means that we have successfully arranged the values around the pivot.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">4. Implemented Code Until Now<\/h3>\n\n\n\n<p>Complete code for the function responsible for selecting a pivot element and then rearranging the elements is given below :<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndef pivot(array, start, end):\n\n#initializing \n    pivot = array&#x5B;start]\n    low = start + 1\n    high = end\n\n\n    while True:\n  \n#moving high towards left\n        while low &lt;= high and array&#x5B;high] &gt;= pivot:\n            high = high - 1\n\n#moving low towards right \n        while low &lt;= high and array&#x5B;low] &lt;= pivot:\n            low = low + 1\n\n#checking if low and high have crossed\n        if low &lt;= high:\n\n#swapping values to rearrange\n            array&#x5B;low], array&#x5B;high] = array&#x5B;high], array&#x5B;low]\n         \n        else:\n#breaking out of the loop if low &gt; high\n            break\n\n#swapping pivot with high so that pivot is at its right # #position \n    array&#x5B;start], array&#x5B;high] = array&#x5B;high], array&#x5B;start]\n\n#returning pivot position\n    return high\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">5. Make recursive calls on two halves of the array <\/h3>\n\n\n\n<p>After rearranging the elements around the pivot, we need to make recursive calls on the two halves of the array. <\/p>\n\n\n\n<p>These calls will repeat themselves until we have arrays of size one. The code for function that makes the recursive calls is given below:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndef quick_sort(array, start, end):\n    if start &gt;= end:\n        return\n\n#call pivot \n    p = pivot(array, start, end)\n#recursive call on left half\n    quick_sort(array, start, p-1)\n#recursive call on right half\n    quick_sort(array, p+1, end)\n<\/pre><\/div>\n\n\n<p>The last two statements make the recursive calls on the left and right halves respectively. <\/p>\n\n\n\n<p>The same process of choosing a pivot and rearranging elements around it is repeated for the left and right halves. <\/p>\n\n\n\n<p>When we do this repeatedly we make sure that each element is placed at its correct position. <\/p>\n\n\n\n<p>Here, &#8216;correct position&#8217; means that all the smaller elements are on the left and all the greater elements are on the right. When all the elements are placed at their correct positions we get a sorted array. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Example of the Quicksort Array<\/h2>\n\n\n\n<p>Let&#8217;s take an example for testing our code. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n&#x5B;5,1,3,9,8,2,7]\n<\/pre><\/div>\n\n\n<p>Let&#8217;s add some code to print the pivot element, left half and right half of the array for each recursive call. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndef quick_sort(array, start, end):\n    if start &gt;= end:\n        return\n\n    p = pivot(array, start, end)\n    print(&quot;Pivot&quot;,array&#x5B;p])\n    print(&quot;left :&quot;, array&#x5B;start:p])\n    print(&quot;right :&quot;,array&#x5B;p+1:end+1])\n    print(&quot;\\n&quot;)\n    quick_sort(array, start, p-1)\n    quick_sort(array, p+1, end)\n<\/pre><\/div>\n\n\n<p>Let&#8217;s run the code with our sample array above. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\narray = &#x5B;5,1,3,9,8,2,7]\n\nquick_sort(array, 0, len(array) - 1)\nprint(array)\n<\/pre><\/div>\n\n\n<p>The output comes out as :<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nPivot 5\nleft : &#x5B;2, 1, 3]\nright : &#x5B;8, 9, 7]\n\n\nPivot 2\nleft : &#x5B;1]\nright : &#x5B;3]\n\n\nPivot 8\nleft : &#x5B;7]\nright : &#x5B;9]\n\n\n&#x5B;1, 2, 3, 5, 7, 8, 9]\n<\/pre><\/div>\n\n\n<p>We can see that for each pivot element the left array contains elements smaller than the pivot and the right array contains the elements greater than the pivot. <\/p>\n\n\n\n<p>Visually we can represent the recursive calls as follows : <\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"512\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/pivot-1024x512.png\" alt=\"Pivot\" class=\"wp-image-9753\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/pivot-1024x512.png 1024w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/pivot-300x150.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/pivot-768x384.png 768w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/pivot.png 1280w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Complete implementation <\/h2>\n\n\n\n<p>The complete implementation for Quicksort is given below : <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndef pivot(array, start, end):\n\n#initializing \n    pivot = array&#x5B;start]\n    low = start + 1\n    high = end\n\n\n    while True:\n  \n#moving high towards left\n        while low &lt;= high and array&#x5B;high] &gt;= pivot:\n            high = high - 1\n\n#moving low towards right \n        while low &lt;= high and array&#x5B;low] &lt;= pivot:\n            low = low + 1\n\n#checking if low and high have crossed\n        if low &lt;= high:\n\n#swapping values to rearrange\n            array&#x5B;low], array&#x5B;high] = array&#x5B;high], array&#x5B;low]\n         \n        else:\n#breaking out of the loop if low &gt; high\n            break\n\n#swapping pivot with high so that pivot is at its right # #position \n    array&#x5B;start], array&#x5B;high] = array&#x5B;high], array&#x5B;start]\n\n#returning pivot position\n    return high\n\n\ndef quick_sort(array, start, end):\n    if start &gt;= end:\n        return\n\n#call pivot \n    p = pivot(array, start, end)\n#recursive call on left half\n    quick_sort(array, start, p-1)\n#recursive call on right half\n    quick_sort(array, p+1, end)\n\n\narray = &#x5B;5,1,3,9,8,2,7]\n\nquick_sort(array, 0, len(array) - 1)\nprint(array)\n\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Conclusion <\/h2>\n\n\n\n<p>This tutorial was about implementing Quicksort in Python. The<strong> worst-case time complexity of Quicksort is O(n<sup>2<\/sup>)<\/strong> and <strong>average-case time complexity is O(n logn).<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Quicksort is a sorting algorithm that follows the policy of divide and conquer. It works on the concept of choosing a pivot element and then arranging elements around the pivot by performing swaps. It recursively repeats this process until the array is sorted. In this tutorial we will learn how QuickSort works and how to [&hellip;]<\/p>\n","protected":false},"author":14,"featured_media":9755,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-9751","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-examples"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/9751","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=9751"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/9751\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/9755"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=9751"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=9751"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=9751"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}