qsort(3) CLIX qsort(3)
NAME
qsort - Provides a quick sort facility
LIBRARY
Standard C Library (libc.a)
SYNOPSIS
void qsort(
char *base ,
unsigned count ,
int sizeof ,
int *compar() );
PARAMETERS
base This first element of the array of elements to be sorted
count The number of elements to be sorted
sizeof The size in characters of each element
compar A comparison function
DESCRIPTION
The qsort() function is an implementation of the quicker-sort algorithm.
It sorts a table of data in place.
The base parameter points to the element at the base of the table. The
count parameter specifies the number of elements in the table. The
comparison function, compar(), is called with two arguments that point to
the elements being compared. As the function must return an integer less
than, equal to, or greater than zero, so must the first argument to be
considered be less than, equal to, or greater than the second.
EXAMPLES
To sort a randomly generated set of numbers:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 100
/* Here is the comparison function! */
int compare_ints(a, b)
int *a, *b;
2/94 - Intergraph Corporation 1
qsort(3) CLIX qsort(3)
{
return((*a == *b) ? 0 : (*a < *b) ? -1 : 1);
}
main()
{
int i;
int array[SIZE];
for(i = 0; i < SIZE; ++i)
array[i] = rand();
qsort(array, SIZE, sizeof(int), (int (*)(const void *, const void *))
compare_ints);
for(i = 0; i < SIZE; ++i)
printf("%i\n", array[i]);
}
NOTES
The pointer to the base of the table should be of type pointer-to-element,
and cast to type pointer-to-character.
The comparison function need not compare every byte, so arbitrary data may
be contained in the elements in addition to the values being compared.
The order in the output of two items which compare as equal is
unpredictable.
RELATED INFORMATION
Functions: bsearch(3), lsearch(3), string(3)
Commands: sort(1)
2 Intergraph Corporation - 2/94