Following is the prototype for bsearch():
void *bsearch(const void *key, const void *buf, size_t num, size_t size, int (*comp)(const void *, const void *));
The bsearch() function performs a binary search on an array of sorted data elements. A binary search is another “divide and conquer” algorithm. The key is compared with the middle element of the array. If it is equal, the search is done. If it is less than the middle element, the item searched for must be in the first half of the array, so a binary search is performed on just the first half of the array. If the key is greater than the middle element, the item searched for must be in the second half of the array, so a binary search is performed on just the second half of the array. Below example(1) shows a simple function that calls the bsearch() function. This listing borrows the function comp() from the previous post, which used qsort(). Below example(2) shows a binary search, performed without calling bsearch(), for a string in a sorted array of strings.
1. An example of how to use bsearch().

2. An implementation of a binary search.

3. An implementation of linear searching.

No comments:
Post a Comment