Does anyone know how the standard binary search function is implemented?
This is the prototype.
void * bsearch (const void*, const void*, size_t, size_t, int (*) (const void *, const void *) );
I’m really curious about how they used void pointers.
I assume you are interested in knowing how
void *pointers are used inbsearch, rather than the actual binary search algorithm itself. The prototype forbsearchis:Here,
void *is used so that any arbitrary type can be searched. The interpretation of the pointers is done by the (user-supplied)comparfunction.Since the pointer
basepoints to the beginning of an array, and an array’s elements are guaranteed to be contiguous,bsearchcan get avoid *pointer to any of thenmembelements in the array by doing pointer arithmetic. For example, to get a pointer to the fifth element in the array (assumingnmemb >= 5):In the above snippet, we couldn’t add
size*ndirectly tobasebecause it is of typevoid *, and arithmetic onvoid *is not defined.