qsort()
does one thing and it does it exceptionally well, it sorts arrays, and does so very efficiently. As noted in the comments, before you can use qsort()
you will need to collect your values in an array rather than separate variables. Once you have an array, using qsort()
is trivial, your only responsibility using qsort is to write the compare()
function.
New users of qsort()
usually have their eyes roll back in their heads when they see the declaration for the function:
int compare (const void *a, const void *b) { ... }
It's actually quite simple. a
and b
are simply pointers to elements of the array to compare. Since qsort()
can handle any type array, the parameter type are void
pointers. If you have an array of int
, a
and b
are just pointers int
(e.g. int*
). You simply need to write your compare function to cast a
and b
to int*
and dereference to compare the int
values with each other.
The return of compare()
is either less than zero (a
sorts before b
), zero (a
and b
are equal) or greater than zero (b
sorts before a
). So a niave compare()
can be as simple as:
int compare (const void *a, const void *b)
{
int x = *(int *)a,
y = *(int *)b;
return x - y;
}
However, there is always a potential for x - y
to overflow with a large negative x
and large y
or large x
and large negative y
. So you generally try and use the differnce between two comparisons to eliminate the potential for overflow, e.g.
int compare (const void *a, const void *b)
{
int x = *(int *)a,
y = *(int *)b;
return (x > y) - (x < y);
}
Now if you take any value of a
and b
the return will either be -1
, 0
or 1
providing the sort information for qsort()
without chance of overflow.
A short example using your values could be written as:
#include <stdio.h>
#include <stdlib.h>
int compare (const void *a, const void *b)
{
int x = *(int *)a,
y = *(int *)b;
return (x > y) - (x < y);
}
void prn_arr (int *arr, size_t nmemb)
{
for (size_t i = 0; i < nmemb; i++)
printf (i ? ", %d" : "%d", arr[i]);
putchar ('\n');
}
int main()
{
int num[] = {8, 6, 2, 4, 1};
size_t nmemb = sizeof num / sizeof *num;
puts ("array before sort:\n");
prn_arr (num, nmemb);
qsort (num, nmemb, sizeof *num, compare);
puts ("\narray after sort:\n");
prn_arr (num, nmemb);
}
Example Use/Output
$ ./bin/qsortnum
array before sort:
8, 6, 2, 4, 1
array after sort:
1, 2, 4, 6, 8
Look things over and let me know if you have further questions.