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_t n, size_t size, int (*compare)(const void *,const void *));

Sorts the array a using the quick-sort algorithm. The array is assumed to have n elements whose size is size.

void *bsearch( const void *key, const void *a, size_t n, size_t size, int (*compare)( const void*, const void* ) );

Searches in a sorted array a for the keyword addressed by key, using the binary search algorithm. The array a is assumed to have n array elements whose size is size.

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.