Searching and Sorting
The following two functions are declared in the header file stdlib.h as general utilities for searching and sorting:
-
voidqsort(void *a, size_tn, size_tsize, int (*compare)(const void *,const void *)); Sorts the array
ausing the quick-sort algorithm. The array is assumed to havenelements 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
afor the keyword addressed bykey, using the binary search algorithm. The arrayais assumed to havenarray 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;
}Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access