Library contents

C bsearch

bsearch searches a sorted array and returns a pointer to a matching element. A null pointer indicates a miss.

A simple example

bsearch

  1. Start with Sorted values 1, 3, 5
  2. Do this Search for 3
  3. Result Found in the middle
A comparison with the middle value is enough to locate 3.

Syntax

C syntax
bsearch(&key, items, count, sizeof items[0], compare)
Run this example in C

Save the program as lesson.c. Use C17 and a Unix-style shell.

cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson

Look up an item in a sorted catalog

A price catalog is already sorted and can contain repeated thresholds. Locate the correct boundary and check what the returned position means when an exact value is absent.

From the programint catalog[] = {10, 20, 30, 40}
First output linefound 30
lesson.c
#include <stdio.h>
#include <stdlib.h>

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

int main(void) {
    int catalog[] = {10, 20, 30, 40};
    int queries[] = {30, 25};
    for (size_t i = 0; i < 2; ++i) {
        const int *item = bsearch(&queries[i], catalog, 4, sizeof catalog[0], compare);
        printf("%s %d\n", item ? "found" : "missing", queries[i]);
    }
    return 0;
}
Output
found 30
missing 25

The catalog must be sorted according to the same ordering used by the lookup. With duplicate keys, any matching element can be returned.

Open Group function reference for bsearch

Advertisements

Locate a numbered tote

A parcel clerk keeps tote numbers in ascending order. Find the specified item in the sorted register. How many smaller entries come before it?

Given4 · 9 · 15 · 22 | seek 15
Worked result2

Find the earliest permit

A permit clerk starts with the smallest valid identifier. Find the specified item in the sorted register. How many smaller entries come before it?

Given3 · 6 · 10 | seek 3
Worked result0