greater than the item is selected. Of this half, the middle item is then again selected.
3.This process is repeated until a match is found or it is shown that the key is not part of the list.
For example, suppose the key (the item you want to find) is 5. Your list contains the following numbers: 1, 2, 5, 12, 23, 24, 34, 35, 38, 45, 47, 50, 60, 65, 66, 76, 78, and 80. The first selection is 38 (the middle item in the list). Because 5 is less than 38, the next selection is 23, (halfway between 1 and 38). Because 5 is smaller than 23, the next selection is 5 (halfway between 1 and 23). This is a match, so the search stops.
The maximum number of comparisons with a binary search is small—in a file of 65,000 items, at most only 16 comparisons must be made. With a linear search, an average of 32,000 comparisons are required.
The winner? A binary search is always the winner when the list can be (or is) sorted. If the list cannot be sorted, a linear search must be performed.
Fortunately, the C compiler provides a binary search function called bsearch(). This function requires a sorted list and the address of a compare function. The bsearch() and bsort() functions use the same compare function, so that only one compare function needs to be written when using either bsearch() or bsort(). In our sorting and searching, we are working with an array of index records, and these index records are what must be dealt with by the compare function. Because with bsort() and bsearch() the compare is passed the address of the array members, the compare function is defined as accepting two pointers to CUSTINDEX structures.
int |
compare(const void *, const void*); |
When the user wants to add a record to the customer database, the program first uses memset() to clear the Customer structure. It then prompts for the name. If the user enters a name, the program processes it.
The code for adding a record follows:
case ‘A’: /* Add a record */ case ‘a’: