Searching and Sorting
The following two functions are declared in the header file stdlib.h as general utilities for searching and sorting:
-
void
qsort
(void *a
, size_tn
, size_tsize
, int (*compare
)(const void *,const void *)); Sorts the array
a
using the quick-sort algorithm. The array is assumed to haven
elements whose size issize
.-
void *
bsearch
( const void *key
, const void *a
, size_tn
, size_tsize
, int (*compare)( const void*, const void* ) ); Searches in a sorted array
a
for the keyword addressed bykey
, using the binary search algorithm. The arraya
is assumed to haven
array elements whose size issize
.
The last parameter to these functions,
compare
, is a pointer to a function that
compares two elements of the array a
. Usually this
function must be defined by you, the programmer. Its parameters are
two pointers to the array elements to be compared. The function must
return a value that is less than, equal to, or greater than
0
to indicate whether the first element is less
than, equal to, or greater than the second. To search or sort an
array of float
values, for example, the following
comparison function could be specified:
int floatcmp( const void* p1, const void* p2 ) { float x = *(float *)p1, y = *(float *)p2; return x <= y ? ( x < y ? -1 : 0) : 1; }
Get C Pocket Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.