Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>At least from your description, you only care about sorting on PRI values, but want the negative values to come after positive ones (but the positive ones to be in order).</p> <p>One easy way to do this is to cast the PRI values to unsigned before doing the comparison. When converted to unsigned, a negative value will be reduced modulo 2<sup>N</sup>-1 so (for example) -1 will convert to UINT_MAX (and, more importantly, all negative numbers will convert to unsigned numbers greater than anything that started out as a positive signed number).</p> <pre><code>typedef struct { int PID; int PRI; } proc; int cmp(void const *a, void const *b) { proc const *aa = (proc const *)a; proc const *bb = (proc const *)b; if ((unsigned)(bb-&gt;PRI) &lt; (unsigned)(aa-&gt;PRI)) return -1; if ((unsigned)(aa-&gt;PRI) &lt; (unsigned)(bb-&gt;PRI)) return 1; return 0; } </code></pre> <p>At the end, instead of returning 0 based only on equality of the PRI values, you may also want to add a comparison of the PIDs, so items will equal PRI values will be sorted by PID. I've left that out for now, since you haven't said that you really need/want it (and it makes the code a bit longer and potentially harder to understand, especially if you're not expecting it to be there).</p> <p>Edit: In case it wasn't clear, this comparison function is intended to work with <code>qsort</code>, and (assuming you do the comparison correctly) a stable sort isn't necessary. You only need a stable sort if you decided go the (nearly always slower) route of sorting first on one field, then doing a second (separate) sort on a second field, rather than comparing on all the relevant fields in a single comparison.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload