全部博文(136)
分类: C/C++
2011-03-15 09:19:05
Here's an implementation for sorting an array of strings, which is a common case. We define a function scmp to cast the arguments and call strcmp to do the comparison.
To sort elements str1 through str[N-1] of an array of strings, qsort must be called with the array, its length, the size of the items being sorted, and the comparison function:
char *str[N];Here's a similar function icmp for comparing integers:
Again, the call to qsort requires the array, its length, the size of the items being sorted, and the comparison function:
int arr[N];
ANSI C also defines a binary search routine, bsearch. Like qsort, bsearch requires a pointer to a comparison function (often the same one used for qsort); it returns a pointer to the matching element or NULL if not found. Here is out HTML loopup routine, rewritten to use bsearch:
As with qsort, the comparison routine receives the address of the items to be compared, so the key must have that type; in this example, we need to construct a fake Nameeval entry that is passed to the comparison routine itself is a function nvcmp that compares two Nameval items by calling strcmp on their string components, ignoring their values:
This is analogous to scmp but differs because the strings are stored as members of a structure.
It's a good idea to use bsearch instead of writing your own. Over the years, binary search has proven suprisingly hard for programmers to get right.
The standard C++ library has a generic algorithm called sort that guarantees O(nlog n) behavior.
The C++ library also has generic binary search routines, with similar notational advantages.