Performs a quick sort.
#include <stdlib.h> | For ANSI compatibility | |
#include <search.h> | Required only for function declarations |
void qsort( void *base, size_t num, size_t width,
int( __cdecl *compare ) ( const void *elem1, const void *elem2) );
base | Start of target array | |
num | Array size in elements | |
width | Element size in bytes | |
compare | Comparison function | |
elem1 | Pointer to the key for the search | |
elem2 | Pointer to the array element to be compared with the key |
The qsort function implements a quick-sort algorithm to sort an array of num elements, each of width bytes. The argument base is a pointer to the base of the array to be sorted. The qsort function overwrites this array with the sorted elements.
The argument compare is a pointer to a user-supplied routine that compares two array elements and returns a value specifying their relationship. The qsort function calls the compare routine one or more times during the sort, passing pointers to two array elements on each call:
compare((void *) elem1, (void *) elem2);
The routine must compare the elements, then return one of the following values:
Value | Meaning |
< 0 | elem1 less than elem2 |
= 0 | elem1 equivalent to elem2 |
> 0 | elem1 greater than elem2 |
The array is sorted in increasing order, as defined by the comparison function. To sort an array in decreasing order, reverse the sense of “greater than” and “less than” in the comparison function.
None.
Standards:ANSI, UNIX
16-Bit:DOS, QWIN, WIN, WIN DLL
32-Bit:DOS32X
/* QSORT.C: This program reads the command-line parameters and
* uses qsort to sort them. It then displays the sorted arguments.
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int compare( void *arg1, void *arg2 ); /* Prototype */
void main( int argc, char **argv )
{
int i;
/* Eliminate argv[0] from sort: */
argv++;
argc—;
/* Sort remaining args using Quicksort algorithm: */
qsort( (void *)argv, (size_t)argc, sizeof( char * ), compare );
/* Output sorted list: */
for( i = 0; i < argc; ++i )
printf( “%s ”, argv[i] );
printf( “\n” );
}
int compare( void *arg1, void *arg2 )
{
/* Compare all of both strings: */
return _stricmp( * ( char** ) arg1, * ( char** ) arg2 );
}
[C:\LIBREF] qsort every good boy deserves favor
boy deserves every favor good