1 2 3 4 5 6 7 8 9

Consider the sorting of an array of chars using qsort

void qsort (char* base, int nel, int width, int (*cmp)(char*, char*) );

base nel
width cmp

The origin of the array of chars
The number of elements in the array The size of each element (bytes)
pointer to a function whose two parameters
are pointers to two char elements.
cmp returns -ve, 0, +ve

For sorting "chars" we might define a compare function:

int CmpChar ( char* a, char* b) {
if ( *a == *b ) {
return 0;
} else {
return ( *a > *b ? 1 : -1 );
}
}

int (*CmpPtr)(); CmpPtr = CmpChar;

// declare a function pointer // initialize it

int buffer[1024] = {23, 37, 14, 99, 81, 62};

qsort ( buffer, 1024, sizeof(char), CmpPtr );

See also Unix quicksort program, King 173-176.

4 February, 1998

5

Copyright University of Alberta