Explain Searching and Sorting method with program and example
The stdlib.h provides 2 useful functions to perform general searching and sorting of data on any type.
The qsort standard library function is very useful function that is designed to sort an array by a key value of any type into ascending order, as long as the elements of the array are of fixed type.
qsort is prototyped (in stdlib.h):
void qsort(void *base, size_t num_elements, size_t element_size,
int (*compare)(void const *, void const *));
Similarly, there is a binary search function, bsearch() which is prototyped (in stdlib.h) as:
void *bsearch(const void *key, const void *base, size_t nel,
size_t size, int (*compare)(const void *, const void *));
Using the same Record structure and record_compare function as the qsort() example (in Chapter 11.3):
typedef struct {
int key;
struct other_data;
} Record;
int record\_compare(void const *a, void const *a)
{ return ( ((Record *)a)->key - ((Record *)b)->key );
}
Also, Assuming that we have an array of array_length Records suitably filled with date we can call bsearch() like this:
Record key;
Record *ans;
key.key = 3; /* index value to be searched for */
ans = bsearch(&key, array, arraylength, sizeof(Record), record_compare);
The function bsearch() return a pointer to the field whose key filed is filled with the matched value of NULL if no match found.
Note that the type of the key argument must be the same as the array elements (Record above), even though only the key.key element is required to be set.