{"id":25234,"date":"2017-10-15T16:04:04","date_gmt":"2017-10-15T10:34:04","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25234"},"modified":"2017-10-15T16:04:04","modified_gmt":"2017-10-15T10:34:04","slug":"iterative-quick-sort","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/iterative-quick-sort\/","title":{"rendered":"Iterative Quick Sort"},"content":{"rendered":"<p>Following is a typical recursive implementation of Quick Sort that uses last element as pivot.<\/p>\n<p><strong>C++<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">c++<\/span> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">\/* A typical recursive C\/C++  implementation of QuickSort *\/<br\/> <br\/>\/* This function takes last element as pivot, places <br\/>   the pivot element at its correct position in sorted <br\/>   array, and places all smaller (smaller than pivot)<br\/>   to left of pivot and all greater elements to right <br\/>   of pivot *\/<br\/>int partition (int arr[], int l, int h)<br\/>{<br\/>    int x = arr[h];<br\/>    int i = (l - 1);<br\/> <br\/>    for (int j = l; j &lt;= h- 1; j++)<br\/>    {<br\/>        if (arr[j] &lt;= x)<br\/>        {<br\/>            i++;<br\/>            swap (&amp;arr[i], &amp;arr[j]);<br\/>        }<br\/>    }<br\/>    swap (&amp;arr[i + 1], &amp;arr[h]);<br\/>    return (i + 1);<br\/>}<br\/> <br\/>\/* A[] --&gt; Array to be sorted, <br\/>  l  --&gt; Starting index, <br\/>  h  --&gt; Ending index *\/<br\/>void quickSort(int A[], int l, int h)<br\/>{<br\/>    if (l &lt; h)<br\/>    {        <br\/>        \/* Partitioning index *\/<br\/>        int p = partition(A, l, h); <br\/>        quickSort(A, l, p - 1);  <br\/>        quickSort(A, p + 1, h);<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p><strong>JAVA<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/ Java program for implementation of QuickSort<br\/>class QuickSort<br\/>{<br\/>    \/* This function takes last element as pivot,<br\/>       places the pivot element at its correct<br\/>       position in sorted array, and places all<br\/>       smaller (smaller than pivot) to left of<br\/>       pivot and all greater elements to right<br\/>       of pivot *\/<br\/>    int partition(int arr[], int low, int high)<br\/>    {<br\/>        int pivot = arr[high];<br\/>        int i = (low-1); \/\/ index of smaller element<br\/>        for (int j=low; j&lt;=high-1; j++)<br\/>        {<br\/>            \/\/ If current element is smaller than or<br\/>            \/\/ equal to pivot<br\/>            if (arr[j] &lt;= pivot)<br\/>            {<br\/>                i++;<br\/> <br\/>                \/\/ swap arr[i] and arr[j]<br\/>                int temp = arr[i];<br\/>                arr[i] = arr[j];<br\/>                arr[j] = temp;<br\/>            }<br\/>        }<br\/> <br\/>        \/\/ swap arr[i+1] and arr[high] (or pivot)<br\/>        int temp = arr[i+1];<br\/>        arr[i+1] = arr[high];<br\/>        arr[high] = temp;<br\/> <br\/>        return i+1;<br\/>    }<br\/> <br\/>    \/* The main function that implements QuickSort()<br\/>      arr[] --&gt; Array to be sorted,<br\/>      low  --&gt; Starting index,<br\/>      high  --&gt; Ending index *\/<br\/>    void qSort(int arr[], int low, int high)<br\/>    {<br\/>        if (low &lt; high)<br\/>        {<br\/>            \/* pi is partitioning index, arr[pi] is<br\/>              now at right place *\/<br\/>            int pi = partition(arr, low, high);<br\/> <br\/>            \/\/ Recursively sort elements before<br\/>            \/\/ partition and after partition<br\/>            qSort(arr, low, pi-1);<br\/>            qSort(arr, pi+1, high);<br\/>        }<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<p><strong>PYTHON<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\"># A typical recursive Python  implementation of QuickSort *\/<br\/>  <br\/># This function takes last element as pivot, places<br\/># the pivot element at its correct position in sorted<br\/># array, and places all smaller (smaller than pivot)<br\/># to left of pivot and all greater elements to right<br\/># of pivot<br\/>def partition(arr,low,high):<br\/>    i = ( low-1 )         # index of smaller element<br\/>    pivot = arr[high]     # pivot<br\/>  <br\/>    for j in range(low , high):<br\/>  <br\/>        # If current element is smaller than or<br\/>        # equal to pivot<br\/>        if   arr[j] &lt;= pivot:<br\/>          <br\/>            # increment index of smaller element<br\/>            i = i+1<br\/>            arr[i],arr[j] = arr[j],arr[i]<br\/>  <br\/>    arr[i+1],arr[high] = arr[high],arr[i+1]<br\/>    return ( i+1 )<br\/>  <br\/># The main function that implements QuickSort<br\/># arr[] --&gt; Array to be sorted,<br\/># low  --&gt; Starting index,<br\/># high  --&gt; Ending index<br\/>  <br\/># Function to do Quick sort<br\/>def quickSort(arr,low,high):<br\/>    if low &lt; high:<br\/>  <br\/>        # pi is partitioning index, arr[p] is now<br\/>        # at right place<br\/>        pi = partition(arr,low,high)<br\/>  <br\/>        # Separately sort elements before<br\/>        # partition and after partition<br\/>        quickSort(arr, low, pi-1)<br\/>        quickSort(arr, pi+1, high)<br\/> <\/code><\/pre> <\/div>\n<p>The above implementation can be optimized in many ways<\/p>\n<p>1) The above implementation uses last index as pivot. This causes worst-case behavior on already sorted arrays, which is a commonly occurring case. The problem can be solved by choosing either a random index for the pivot, or choosing the middle index of the partition or choosing the median of the first, middle and last element of the partition for the pivot. (See this for details)<\/p>\n<p>2) To reduce the recursion depth, recur first for the smaller half of the array, and use a tail call to recurse into the other.<\/p>\n<p>3) Insertion sort works better for small subarrays. Insertion sort can be used for invocations on such small arrays (i.e. where the length is less than a threshold t determined experimentally). For example, this library implementation of qsort uses insertion sort below size 7.<\/p>\n<p>Despite above optimizations, the function remains recursive and uses function call stack to store intermediate values of l and h. The function call stack stores other bookkeeping information together with parameters. Also, function calls involve overheads like storing activation record of the caller function and then resuming execution.<\/p>\n<p>The above function can be easily converted to iterative version with the help of an auxiliary stack. Following is an iterative implementation of the above recursive code.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Output:<\/strong><\/p>\n<pre>1 2 2 3 3 3 4 5<\/pre>\n<p>The above mentioned optimizations for recursive quick sort can also be applied to iterative version.<\/p>\n<p>1) Partition process is same in both recursive and iterative. The same techniques to choose optimal pivot can also be applied to iterative version.<\/p>\n<p>2) To reduce the stack size, first push the indexes of smaller half.<\/p>\n<p>3) Use insertion sort when the size reduces below a experimentally calculated threshold.<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Iterative Quick Sort &#8211; Searching and Sorting &#8211; Partition process is same in both recursive and iterative. The same techniques to choose optimal pivot can also be applied to iterative version.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,83502,71670],"tags":[71706,70892,72420,72418,72417,70556,72422,71720,72416,70895,72411,72421,72412,72428,72429,70969,71263,72436,71267,72437,72434,71172,71693,72426,72415,72215,70046,71712,71717,71721,72413,71145,72425,71303,72424,70530,71265,72216,72432,71677,71722,72414,72423,71696,72430,71719,70977,72427,72419,72431,72217,72433,72435,70967],"class_list":["post-25234","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-quick-sort","category-searching-and-sorting","tag-algorithm-for-quicksort","tag-best-sorting-algorithm","tag-c-program-for-quicksort-using-arrays","tag-c-quicksort","tag-c-quicksort-example","tag-complexity-of-quicksort","tag-dual-pivot-quicksort","tag-example-of-quicksort","tag-explain-quicksort-with-example","tag-fastest-sorting-algorithm","tag-iterative-quick-sort-searching-and-sorting","tag-java-pivot","tag-java-quicksort","tag-java-quicksort-code","tag-java-quicksort-example","tag-java-sorting-algorithms","tag-merge-sort-java","tag-pivot-java","tag-quick-sort-algorithm","tag-quick-sort-example-with-explanation","tag-quick-sort-method","tag-quick-sort-program","tag-quick-sort-program-in-c","tag-quick-sort-program-in-data-structure-using-c","tag-quick-sort-program-using-c","tag-quick-sort-pseudocode","tag-quicksort","tag-quicksort-algorithm-with-example","tag-quicksort-animation","tag-quicksort-c-code","tag-quicksort-c-code-example","tag-quicksort-c","tag-quicksort-c-program-code","tag-quicksort-code","tag-quicksort-code-java","tag-quicksort-complexity","tag-quicksort-example","tag-quicksort-example-step-by-step","tag-quicksort-example-step-by-step-explanation","tag-quicksort-explained","tag-quicksort-explanation-with-example","tag-quicksort-implementation","tag-quicksort-implementation-java","tag-quicksort-in-c","tag-quicksort-in-c-code","tag-quicksort-in-data-structure-with-example","tag-quicksort-java","tag-quicksort-java-implementation","tag-quicksort-partition","tag-quicksort-partition-java","tag-quicksort-python","tag-quicksort-simple-example","tag-quicksort-step-by-step-example","tag-sorting-algorithms-java"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25234","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=25234"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25234\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25234"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25234"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25234"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}