qsort

The qsort function is used to sort an array of values, using a comparison function that is given as a parameter to qsort. The qsort function uses internally the quicksort algorithm to sort arrays.

The qsort function requires four arguments. The first argument is a pointer to the array that will be sorted by the function. The second argument is the number of elements in this array. The third argument is the size of one element in memory, and is usually found using the sizeof operator. Finally, the fourth parameter is a pointer to a function that is used for comparison purposes.

The comparison must have the following signature:

int func(const void *, const void *);

The comparison function receives two parameters. They are the elements that need to be compared. They come as void pointers because qsort doesn't know what is the type of the objects that are being compared. Thus, we need to convert these pointers into pointers to the data type used in the original array.

The return value of the comparison function is similar to the return value of strcmp. It should return 0 if the elements are the same, -1 if the first element is less than the second, and 1 otherwise.

The following code shows an example of qsort in use:

#include <stdlib.h>
#include <stdio.h>

#define NUM_INT 10

int a[NUM_INT] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};

int compare(const void *aa, const void *bb)
{
        int a = *(int *)aa;
        int b = *(int *)bb;
        return a - b;
}

int main()
{
        int i;
        qsort(a, NUM_INT, sizeof(int), compare);
        for (i=0; i<NUM_INT; i++)
                printf("%d ", a[i]);
        return 0;
}

The output of this program is:

0 1 2 3 4 5 6 7 8 9
Article created on 2008-08-19 22:06:52

Post a comment