{"id":5650,"date":"2022-12-01T00:01:07","date_gmt":"2022-12-01T08:01:07","guid":{"rendered":"https:\/\/c-for-dummies.com\/blog\/?p=5650"},"modified":"2022-12-09T07:18:11","modified_gmt":"2022-12-09T15:18:11","slug":"quick-sorting-structures","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=5650","title":{"rendered":"Quick Sorting Structures"},"content":{"rendered":"<h2>Difficulty: &#9733; &#9733; &#9733; &#9733;<\/h2>\n<p>I&#8217;ve covered the miraculous <em>qsort()<\/em> function <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=1258\">elsewhere in this blog<\/a>. It&#8217;s nifty, allowing you to sort all kinds of data with your only job being to code a <em>compare()<\/em> function. Most coders these days just copy-paste this function and call it good. But for sorting an array of structures, more brain muscle is required.<br \/>\n<!--more--><br \/>\nAs a review, the <em>qsort()<\/em> function has four arguments:<\/p>\n<p><code>void qsort(void *base, size_t nel, size_t width, int (*compar)(const void *, const void *));<\/code><\/p>\n<p>The <code>*base<\/code> is the start of the array or data to sort; <code>nel<\/code> is the number of elements; <code>width<\/code> is the size of each element (most likely the datatype), and <code>*compar()<\/code> is a function that compares the data, spawning the sort.<\/p>\n<p>The <em>compar()<\/em> function has a very specific format. Here\u2019s what most programmers purloin from StackOverflow:<\/p>\n<p><code>int compare(const void *a, const void *b)<br \/>\n{<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;return( *(int *)a - *(int *)b);<br \/>\n}<\/code><\/p>\n<p>Effectively, the <em>return<\/em> statement determines the difference between two elements in the array, generating a value negative, zero, or positive. The <em>qsort()<\/em> function uses this result to sort the list. Changing the expression&#8217;s variable order reverses the sort.<\/p>\n<p>And that&#8217;s about as much thought as anyone puts into the task &mdash; unless faced with something like the sample code shown below.<\/p>\n<h3><a href=\"https:\/\/github.com\/dangookin\/C-For-Dummies-Blog\/blob\/master\/2022_12_01-Lesson.c\" rel=\"noopener\" target=\"_blank\">2022_12_01-Lesson.c<\/a><\/h3>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n#include &lt;stdlib.h&gt;\r\n\r\nstruct film {\r\n    char title[32];\r\n    int year;\r\n};\r\n\r\nint compare(const void *a, const void *b)\r\n{\r\n}\r\n\r\nint main()\r\n{\r\n    const int size = 9;\r\n    struct film bond[size] = {\r\n        { \"Casino Royale\", 2006 },\r\n        { \"Dr. No\", 1962 },\r\n        { \"GoldenEye\", 1995 },\r\n        { \"Goldfinger\", 1964 },\r\n        { \"Moonraker\", 1979 },\r\n        { \"Octopussy\", 1983 },\r\n        { \"Skyfall\", 2012 },\r\n        { \"Spectre\", 2015 },\r\n        { \"Thunderball\", 1965 }\r\n    };\r\n    int x;\r\n\r\n    <span class=\"comments\">\/* sort the list by year *\/<\/span>\r\n    qsort(bond,size,sizeof(struct film),compare);\r\n\r\n    <span class=\"comments\">\/* output results *\/<\/span>\r\n    for( x=0; x&lt;size; x++ )\r\n        printf(\"%d, %s\\n\",\r\n                bond[x].year,\r\n                bond[x].title\r\n              );\r\n\r\n    return(0);\r\n}<\/pre>\n<p>An array of James Bond films is presented as <code>bond[]<\/code>. Each structure contains a movie name and the year it was released.<\/p>\n<p>The <em>qsort()<\/em> function is called at Line 30, which sorts the list by year. A <em>for<\/em> loop outputs the results, which looks like this:<\/p>\n<p><code>1962, Dr. No<br \/>\n1964, Goldfinger<br \/>\n1965, Thunderball<br \/>\n1979, Moonraker<br \/>\n1983, Octopussy<br \/>\n1995, GoldenEye<br \/>\n2006, Casino Royale<br \/>\n2012, Skyfall<br \/>\n2015, Spectre<\/code><\/p>\n<p>Your task is to code the <em>compare()<\/em> function. You must deal with the <code>year<\/code> member in the <em>film<\/em> structure, comparing each value and processing the results to create a proper sort.<\/p>\n<p>Yes, this task is a bastard. When faced with this challenge myself a few months back, I gave up and did something other than a quick sort. But the problem persisted because I knew a solution was possible! You can discover it as well, providing you properly deal with the <em>const void<\/em> pointers and somehow mangle them properly to obtain the <code>year<\/code> member from each structure passed to the <em>compare()<\/em> function.<\/p>\n<p>Have fun! <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=5660\">Click here<\/a> to view my solution, but try this exercise on your own before you peek to see what I did.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Yes, you can use the <em>qsort()<\/em> (quick sort) to sort just about anything, even an array of structures. Getting the <em>compare()<\/em> function correct, however, is a tough pickle. <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=5650\">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":[3],"tags":[],"class_list":["post-5650","post","type-post","status-publish","format-standard","hentry","category-exercise"],"_links":{"self":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5650","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=5650"}],"version-history":[{"count":4,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5650\/revisions"}],"predecessor-version":[{"id":5679,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5650\/revisions\/5679"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=5650"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=5650"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=5650"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}