qsort() Perform Quick Sort
#include <search.h> Required for declarations only
void qsort(base,num,width,compare);
char *base; Pointer to base of search data
unsigned num, width; Number and width of elements
int (*compare)(); Pointer to compare function
qsort() uses a quick-sort algorithm to sort an array of 'num'
elements. Each element is 'width' bytes in size. 'base' points to
the base of the array to be sorted. qsort() overwrites this array
with the sorted elements.
'compare' points to a user-supplied routine that qsort calls one or
more times, each time passing it pointers to two array elements to be
compared. 'compare' returns one of the following values, based on the
results of the comparison:
< 0: 'element1' < 'element2'
0 'element1' == 'element2'
> 0 'element1' > 'element2'
Returns: There is no return value.
Notes: qsort() will make repeated calls to the 'compare' routine
during the search. On each call to 'compare', 'key' will
be compared with one of the elements of 'base'.
-------------------------------- Example ---------------------------------
The following statements print out an array, sort the array and print
it again.
#include <search.h>
#include <stdio.h>
#include <string.h>
int vals[] = {10,90,30,70,50,60,40,80,20,100};
int num = 10, x;
int cmp();
main()
{
for (x = 0; x < num; x++)
printf("%d ",vals[x]);
printf("\n");
qsort(vals,num,sizeof(int),cmp);
for (x = 0; x < num; x++)
printf("%d ",vals[x]);
}
int cmp(n1,n2)
int *n1;
int *n2;
{
return(*n1 - *n2);
}
Seealso:
This page last updated on Fri Nov 30 10:48:32 MSK 2001
Copyright © 1992-2001, Vitaly Filatov, Moscow, Russia
Webmaster