C bsearch() Function

Beginner
7 min read
Updated: Nov 2026
3 examples
<stdlib.h>

Definition

The C bsearch() function searches a sorted array efficiently. It repeatedly compares the key with a middle element and discards half of the remaining range. If duplicates exist, which matching element is returned is unspecified.

This function is declared in <stdlib.h>. Its contract matters as much as its call: validate every required precondition, check any documented sentinel, and keep ownership or host effects clear in the surrounding code. Success returns a pointer to one matching element. Failure to find a match returns NULL; check before dereferencing. The examples below move from the direct call to an edge condition and a practical use.

Syntax

Start with this concrete bsearch() call:

C
bsearch(&key, values, count, sizeof values[0], compare_int);
CallWhat it does
bsearch(&key, values, count, sizeof values[0], compare_int);Searches a sorted array efficiently using the concrete values shown.

Include <stdlib.h>. Also include headers that declare any types, limits, locale tools, or I/O functions used around the call.

Library declaration
C
void *bsearch(const void *key, const void *base, size_t count, size_t size, int (*compare)(const void *, const void *));

Parameters

ParameterDescription
keyPointer to the value being sought.
basePointer to the first element of a sorted array.
countNumber of elements.
sizeSize of each element in bytes.
compareComparator returning negative, zero, or positive for key versus element.

Return Value

Return ValueDescription
Pointer to elementA matching array element was found.
NULLNo matching element exists.

C Examples

Example 1 — Find a present value

This complete program demonstrates a distinct part of the bsearch() contract and checks the result or precondition that matters for the scenario.

C
#include <stdio.h>
#include <stdlib.h>

static int compare_int(const void *a, const void *b) {
    int left = *(const int *)a;
    int right = *(const int *)b;
    return (left > right) - (left < right);
}

int main(void){int a[]={1,3,5,7,9},key=7;int *p=bsearch(&key,a,5,sizeof a[0],compare_int);if(p) printf("found %d\n",*p);}

How It Works

  1. Step 1. Start with an array already sorted by compare_int.
  2. Step 2. Pass the address of the search key.
  3. Step 3. bsearch() narrows the candidate range using the comparator.
  4. Step 4. A non-NULL result points at the matching element.

Example 2 — Handle a missing value

This complete program demonstrates a distinct part of the bsearch() contract and checks the result or precondition that matters for the scenario.

C
#include <stdio.h>
#include <stdlib.h>

static int compare_int(const void *a, const void *b) {
    int left = *(const int *)a;
    int right = *(const int *)b;
    return (left > right) - (left < right);
}

int main(void){int a[]={2,4,6},key=5;int *p=bsearch(&key,a,3,sizeof a[0],compare_int);puts(p?"found":"not found");}

How It Works

  1. Step 1. Keep the array in ascending order.
  2. Step 2. Search for a value between two entries.
  3. Step 3. No comparator equality is found.
  4. Step 4. The returned NULL pointer selects the not-found branch.

Example 3 — Sort before searching

This complete program demonstrates a distinct part of the bsearch() contract and checks the result or precondition that matters for the scenario.

C
#include <stdio.h>
#include <stdlib.h>

static int compare_int(const void *a, const void *b) {
    int left = *(const int *)a;
    int right = *(const int *)b;
    return (left > right) - (left < right);
}

int main(void){int a[]={8,1,4,2},key=4;qsort(a,4,sizeof a[0],compare_int);int *p=bsearch(&key,a,4,sizeof a[0],compare_int);printf("%s\n",p?"found":"missing");}

How It Works

  1. Step 1. Begin with data that is not ordered.
  2. Step 2. Sort using the exact comparator intended for search.
  3. Step 3. Call bsearch() only after ordering is established.
  4. Step 4. The matching pointer confirms the lookup.

Frequently Asked Questions

bsearch() searches a sorted array efficiently. It repeatedly compares the key with a middle element and discards half of the remaining range. If duplicates exist, which matching element is returned is unspecified.
Include <stdlib.h> before calling bsearch().
Success returns a pointer to one matching element. Failure to find a match returns NULL; check before dereferencing.
The array must already be sorted according to the same ordering implemented by the comparator. Avoid subtraction comparators because signed overflow can break ordering.
The function is specified by the C standard library. Exact limits, locale behavior, environment behavior, allocation capacity, or host effects can still vary where relevant.

Next: calloc()

Continue through the C stdlib.h tutorials.

calloc() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful