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.

Categorystdlib.h utilities
KindLibrary function
Header<stdlib.h>
C standardC89 / C90

📝 Syntax

void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));

⚙️ Parameters

key RequiredA pointer to the key to search for.
base RequiredA pointer to the first element of the sorted array.
nmemb RequiredThe number of array elements.
size RequiredThe size of each element in bytes.
compar RequiredCompares 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 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 *.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏