{"id":1269,"date":"2015-03-28T00:01:42","date_gmt":"2015-03-28T07:01:42","guid":{"rendered":"http:\/\/c-for-dummies.com\/blog\/?p=1269"},"modified":"2015-04-04T12:40:07","modified_gmt":"2015-04-04T19:40:07","slug":"inside-the-quicksort","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=1269","title":{"rendered":"Inside the Quicksort"},"content":{"rendered":"<p>The Internet is littered with plenty of good explanations of how the quicksort works. The definition at <a href=\"https:\/\/en.wikipedia.org\/wiki\/Quicksort\" target=\"_blank\">Wikipedia<\/a> graphically illustrates the process, which is commonly called &#8220;divide and conquer.&#8221; I&#8217;ve stolen the Wikipedia illustration and placed it into Figure 1.<br \/>\n<!--more--><br \/>\n<div style=\"width: 290px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/upload.wikimedia.org\/wikipedia\/commons\/6\/6a\/Sorting_quicksort_anim.gif\" width=\"280\" height=\"214\" class \/><p class=\"wp-caption-text\">Figure 1. A graphical illustration of the quicksort process. (Courtesy WikiMedia)<\/p><\/div><\/p>\n<p>As with a bubble sort, the quicksort eventually gets around to swapping items to order the array elements, but that swapping takes place only when necessary. Contrast that approach with the bubble sort, where all elements are exhaustively compared with each other. That&#8217;s why the bubble sort is inefficient.<\/p>\n<p>The quicksort creates a center point or <em>pivot<\/em>. The algorithm examines values left and right of the pivot. Values are swapped when they&#8217;re less than or greater than the pivot point. This process takes place recursively to scan the entire range of values.<\/p>\n<p>Don&#8217;t worry if my explanation doesn&#8217;t clear the air for you. The bottom line with the quicksort is that a lot less swapping takes place than in a bubble sort.<\/p>\n<p>The following code contains my variation on the quicksort algorithm. Unlike other examples you&#8217;ll find on the Interwebs, I tried to make mine readable as opposed to clever.<\/p>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n#include &lt;stdlib.h&gt;\r\n#include &lt;time.h&gt;\r\n\r\n#define SIZE 40\r\n\r\nvoid quicksort(int array[], int size);\r\n\r\nint main()\r\n{\r\n    int x,original[SIZE],sorted[SIZE];\r\n\r\n    srand((unsigned)time(NULL));\r\n    <span class=\"comments\">\/* populate arrays *\/<\/span>\r\n    for(x=0;x&lt;SIZE;x++)\r\n        original[x] = sorted[x] = (rand() % 100)+1;\r\n\r\n    <span class=\"comments\">\/* do the quicksort *\/<\/span>\r\n    quicksort(sorted,SIZE);\r\n\r\n    <span class=\"comments\">\/* display the results *\/<\/span>\r\n    puts(\"Org\\tSorted\");\r\n    for(x=0;x&lt;SIZE;x++)\r\n        printf(\"%3d\\t%3d\\n\",original[x],sorted[x]);\r\n\r\n    return(0);\r\n}\r\n\r\n<span class=\"comments\">\/*\r\n   Quicksort routine\r\n*\/<\/span>\r\nvoid quicksort(int array[], int size)\r\n{\r\n    int left,right,pivot,temp;\r\n\r\n    if(size &lt; 2)            <span class=\"comments\">\/* stop recursion *\/<\/span>\r\n        return;\r\n    pivot = array[size\/2];  <span class=\"comments\">\/* set pivot point, value *\/<\/span>\r\n    right = size-1;\r\n    left = 0;\r\n    while(1)\r\n    {                       <span class=\"comments\">\/* scan for a swapping point *\/<\/span>\r\n        while(array[left] &lt; pivot)\r\n            ++left;\r\n        while(pivot &lt; array[right])\r\n            right--;\r\n        if(left &gt;= right)   <span class=\"comments\">\/* stop if it's not found *\/<\/span>\r\n            break;\r\n                            <span class=\"comments\">\/* swap the values *\/<\/span>\r\n        temp = array[left];\r\n        array[left] = array[right];\r\n        array[right] = temp;\r\n        left++;             <span class=\"comments\">\/* keep looking *\/<\/span>\r\n        right--;\r\n    }\r\n                            <span class=\"comments\">\/* divide and search again *\/<\/span>\r\n    quicksort(array,left);\r\n    quicksort(array+left,size-left);\r\n}<\/pre>\n<p>In the code, two arrays are created, <code>original[]<\/code> and <code>sorted[]<\/code>. Both contain the same values, set at Line 16, but only the <code>sorted[]<\/code> array is manipulated by using the <em>quicksort()<\/em> function. That way you can see before and after in the program&#8217;s output.<\/p>\n<p>Here is sample output, which I truncated to fit on this webpage:<\/p>\n<pre><code>Org\tSorted\r\n 29\t  1\r\n 97\t  2\r\n 96\t 11\r\n 26\t 17\r\n 11\t 17\r\n 85\t 19\r\n 66\t 22\r\n ...     ...\r\n 30\t 93\r\n 48\t 95\r\n 22\t 96\r\n 72\t 96\r\n 46\t 97\r\n  1\t 97<\/code><\/pre>\n<p>Of course, you can always use the <em>qsort()<\/em> function, as demonstrated in <a href=\" http:\/\/c-for-dummies.com\/blog\/?p=1258\">last week&#8217;s Lesson<\/a>, which saves a dozen or so lines of code. By viewing the quicksort function in detail, however, you learn more about how it works. It might also help you understand and appreciate recursion.<\/p>\n<p>If you don&#8217;t understand recursion, starting by reading my series of Lessons: <a href=\"http:\/\/c-for-dummies.com\/blog\/?p=1060\">click here<\/a>.<\/p>\n<p>In <a href=\" http:\/\/c-for-dummies.com\/blog\/?p=1287\">next week&#8217;s Lesson<\/a>, I cover the process of sorting an array of strings by using the <em>qsort()<\/em> function.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The <em>qsort()<\/em> function does its magic thanks to recursion. <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=1269\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-1269","post","type-post","status-publish","format-standard","hentry","category-main"],"_links":{"self":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1269","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1269"}],"version-history":[{"count":7,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1269\/revisions"}],"predecessor-version":[{"id":1318,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1269\/revisions\/1318"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1269"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1269"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1269"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}