.TH qsort() "" "" "General Function (libc)"
.PC "Sort arrays in memory"
.B "#include <stdlib.h>"
\fBvoid qsort(\fIdata\^\fB, \fIn\^\fB, \fIsize\^\fB, \fIcomp\^\fB)\fR
\fBchar *\fIdata\^\fB; int \fIn\^\fB, \fIsize\^\fB; int (*\fIcomp\^\fB)(\|)\^\fB;\fR
.PP
.II "Hoare, C.A.R."
.B qsort()
is a generalized algorithm for sorting arrays of data in memory,
using C. A. R. Hoare's \*(QLquicksort\*(QR algorithm.
.B qsort()
works with a sequential array of memory called
.IR data ,
which is divided into
.I n
parts of
.I size
bytes each.
In practice,
.I data
is usually an array of pointers or structures, and
.I size
is the
.B sizeof
the pointer or structure.
Each routine compares pairs of items and exchanges them as required.
The user-supplied routine to which
.I comp
points performs the comparison.
It is called repeatedly, as follows: 
.DM
	(*comp)(p1, p2)
	char *p1, *p2;
.DE
.PP
Here,
.I p1
and
.I p2
each point to a block of
.I size
bytes in the
.I data
array.
In practice, they are usually pointers to pointers or pointers
to structures.
The comparison routine must return a negative, zero, or positive result,
depending on whether
.I p1
is logically less than, equal to, or greater than
.IR p2 ,
respectively.
.SH Example
For an example of this function, see the entry for
.BR malloc() .
.SH "See Also"
.Xr "libc," libc
.Xr "shellsort()," shellsort
.Xr "strcmp()," strcmp
.Xr "stdlib.h," stdlib.h
.Xr "strncmp()" strncmp
.br
\fIThe Art of Computer Programming,\fR vol. 3
.br
\*(AS, \(sc7.10.5.2
.br
\*(PX Standard, \(sc8.1
.SH Notes
The \*(CO library also includes the sorting function
.BR shellsort() .
These functions use different algorithms for sorting items; each algorithm has
its strengths and weaknesses.
In general, the quicksort algorithm is faster than the shellsort
algorithm for large arrays, whereas the shellsort
algorithm is faster for small arrays (say, 50 items or fewer).
The quicksort algorithm also performs poorly on arrays with
a small number of keys, e.g., an array of 1,000 items whose keys
are all `7' and `8'.
.PP
To get around these limitations, the \*(CO implementation of
.B qsort()
has an adaptive algorithm that recognizes when the quicksort
algorithm is performing badly, and calls
.B shellsort()
in its place.
