C programming
binary search
standard library
algorithms
C language

Is there a Binary Search method in the C standard library?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Yes. The C standard library provides binary search through the bsearch function in stdlib.h. It is a low-level API designed for sorted arrays, so it works well when you already have contiguous memory and a comparison function, but it does not sort the data or provide insertion-point information for missing keys.

The bsearch Function

The standard signature is:

c
1void *bsearch(
2    const void *key,
3    const void *base,
4    size_t nmemb,
5    size_t size,
6    int (*compar)(const void *, const void *)
7);

It returns:

  • a pointer to a matching element if found
  • 'NULL if no matching element exists'

The array must already be sorted according to the same ordering rule used by the comparator.

Basic Example with Integers

c
1#include <stdio.h>
2#include <stdlib.h>
3
4static int compare_ints(const void *a, const void *b) {
5    int left = *(const int *)a;
6    int right = *(const int *)b;
7
8    if (left < right) return -1;
9    if (left > right) return 1;
10    return 0;
11}
12
13int main(void) {
14    int values[] = {2, 4, 6, 8, 10, 12};
15    int key = 8;
16
17    int *found = bsearch(&key, values, 6, sizeof(int), compare_ints);
18
19    if (found != NULL) {
20        printf("Found: %d\n", *found);
21    } else {
22        printf("Not found\n");
23    }
24
25    return 0;
26}

This works because the array is already sorted and the comparison function matches that ordering.

qsort and bsearch Often Go Together

In C, qsort and bsearch are natural companions. qsort sorts the array and bsearch searches it using the same comparator.

c
1#include <stdio.h>
2#include <stdlib.h>
3
4static int compare_ints(const void *a, const void *b) {
5    int left = *(const int *)a;
6    int right = *(const int *)b;
7    return (left > right) - (left < right);
8}
9
10int main(void) {
11    int values[] = {42, 7, 13, 99, 5, 18};
12    size_t count = sizeof(values) / sizeof(values[0]);
13    int key = 13;
14
15    qsort(values, count, sizeof(int), compare_ints);
16
17    int *found = bsearch(&key, values, count, sizeof(int), compare_ints);
18
19    if (found) {
20        printf("Found: %d\n", *found);
21    }
22
23    return 0;
24}

This is the typical standard-library workflow for sorted array lookup in C.

Arrays of Structs

bsearch becomes especially useful with arrays of records. You can search by a key field if the comparator knows how to compare the search key against an element.

c
1#include <stdio.h>
2#include <stdlib.h>
3
4typedef struct {
5    int id;
6    const char *name;
7} User;
8
9static int compare_user_id(const void *key, const void *element) {
10    int target = *(const int *)key;
11    const User *user = (const User *)element;
12    return (target > user->id) - (target < user->id);
13}
14
15int main(void) {
16    User users[] = {
17        {10, "Ana"},
18        {20, "Ben"},
19        {30, "Cara"}
20    };
21    int key = 20;
22
23    User *found = bsearch(&key, users, 3, sizeof(User), compare_user_id);
24
25    if (found) {
26        printf("%s\n", found->name);
27    }
28
29    return 0;
30}

This is a common pattern when you want a fast lookup in a sorted record array without introducing a separate hash table.

What bsearch Does Not Provide

bsearch is useful, but it is intentionally minimal. It does not:

  • sort the array for you
  • tell you where a missing element should be inserted
  • guarantee which matching element you get if duplicates exist
  • work on linked lists or other non-array data structures

If you need lower-bound or upper-bound semantics, or exact insertion positions, you usually write a custom binary search instead of relying on bsearch alone.

Comparator Quality Matters

The comparator must define the same ordering that the array was sorted with. If the array order and comparator disagree, the search result is unreliable.

Also avoid simplistic comparator code like:

c
// return *(const int *)a - *(const int *)b;

That can overflow for large integers. The explicit comparison pattern is safer.

When bsearch Is the Right Tool

Use bsearch when:

  • the data is in a sorted array
  • the dataset is read-mostly
  • you want a standard-library solution
  • you do not need insertion-point information

If your data structure or query requirements do not match those assumptions, another approach may be better.

Common Pitfalls

The biggest mistake is calling bsearch on an unsorted array. Another is using a comparator that does not match the actual array ordering. Developers also often expect bsearch to report the insertion position for a missing key, which it does not. Finally, duplicate values can be surprising because bsearch does not guarantee which matching element it returns when more than one element compares equal.

Summary

  • The C standard library provides binary search as bsearch in stdlib.h.
  • 'bsearch works on sorted arrays and returns a pointer to a matching element or NULL.'
  • Use the same comparison logic for both sorting and searching.
  • 'qsort and bsearch are commonly paired.'
  • If you need insertion-point or duplicate-range behavior, write a custom search instead.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.