bsearch() Binary-search a sorted array
bsearch() Binary-search a sorted array
bsearch() binary-searches an array sorted with its comparator, returning a match or NULL. Which duplicate match is returned is unspecified.
| Category | stdlib.h utilities |
|---|---|
| Kind | Library function |
| Header | <stdlib.h> |
| C standard | C89 / C90 |
📝 Syntax
void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
⚙️ Parameters
| key Required | A pointer to the key to search for. |
|---|---|
| base Required | A pointer to the first element of the sorted array. |
| nmemb Required | The number of array elements. |
| size Required | The size of each element in bytes. |
| compar Required | Compares the key with an array element and returns negative, zero, or positive according to their ordering. |
Returns: Returns a void pointer to a matching element if one is found, or NULL otherwise.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
Found 15
⚠️ Warning The array must be sorted with the same ordering used by the comparator. Searching an unsorted or differently ordered array is unreliable.
💡 Tip The example calls qsort() before searching for key and reuses its comparator, ensuring that both operations use the same ordering.
🏷️ Related stdlib.h functions
📚 Related Tutorials
❓ FAQ
QWhy does bsearch require a sorted array?
AA binary search eliminates half the remaining range after comparing the middle element; it needs the global ordering to choose the correct side.
QWhich matching element does bsearch return when duplicates exist?
AThe standard does not specify which match is returned, only that it is a matching element. Additional boundary handling is needed to find the first or last match.
QShould the key argument to bsearch be a value or an address?
APass a pointer to the key object; the comparator receives it as its first argument. When searching an int array, normally define int key and pass &key, using the same comparator that sorted the array. Do not cast an integer value to a pointer merely because the parameter is void *.