Previous Page
Next Page

16.7. Searching and Sorting

Table 16-20 lists the standard library's two general searching and sorting functions, which are declared in the header stdlib.h. The functions to search the contents of a string are listed in the section "String Processing," earlier in this chapter.

Table 16-20. Searching and sorting functions



Sort an array

qsort( )

Search a sorted array

bsearch( )

These functions feature an abstract interface that allows you to use them for arrays of any element type. One parameter of the qsort( ) function is a pointer to a call-back function that qsort( ) can use to compare pairs of array elements. Usually you will need to define this function yourself. The bsearch( ) function, which finds the array element designated by a "key" argument, uses the same technique, calling a user-defined function to compare array elements with the specified key.

The bsearch( ) function uses the binary search algorithm , and therefore requires that the array be sorted beforehand. Although the name of the qsort( ) function suggests that it implements the quick-sort algorithm, the standard does not specify which sorting algorithm it uses.

Previous Page
Next Page