qsort() is found in stdlib.h. Its prototype is:
Code:
void qsort( void *base, size_t nel, size_t size, int (*compar)(const void *, const void *) );
This may look intimidating, but it doesn't have to be. Let's take a look at each argument:- base - The memory address of the list of items to sort. If your entries are in an array, simply put the array name here.
nel - The number of elements in your array.
size - The size of each element in the array (not the size of the entire array).
compar - The address of the function used to compare any two elements in your array.
Assuming you are comparing strings, you may either use strcmp() as your compare function or encapsulate it in your own function:
Code:
int compare( void *a, void *b )
{
return ( strcmp(a,b) );
}
Here's a quick example:
Code:
#include <stdlib.h>
#include <stdio.h>
int compare( void *a, void *b )
{
return strcmp( a, b );
}
int main( void )
{
int i;
char array[5][10] = { "One", "Two", "Three", "Four", "Five" };
qsort( array, 5, 10, &compare );
for ( i=0; i<5; i++ )
printf( "%s\n", array[i] );
return 0;
}
The output is: