Friday, 3 February 2012

What is the easiest searching method to use?

Just as qsort() was the easiest sorting method, because it is part of the standard library, bsearch() is the easiest searching method to use.

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.

Another simple searching method is a linear search. A linear search is not as fast as bsearch() for searching among a large number of items, but it is adequate for many purposes. A linear search might be the only method available, if the data isn’t sorted or can’t be accessed randomly. A linear search starts at the beginning and sequentially compares the key to each element in the data set. Below example shows a linear search.

3. An implementation of linear searching.


No comments:

Post a Comment