Library contents

C bsearch

Binary search looks for a matching element in a sorted array.

A simple example

bsearch

  1. Start with 1, 2, 3
  2. Do this Look for 2
  3. Result Found
The requested value matches the second element.

Syntax

C syntax
bsearch(&wanted, prices, count, sizeof prices[0], compare)
Run these examples in C

Save one example at a time as lesson.c. Use C17 and a Unix-style shell.

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

Look up an offer price in a sorted list

A retailer checks a list of prices for a particular offer. Decide whether the question requires the presence of the price, its position or the number of occurrences before interpreting the result.

From the programint prices[] = {3, 3, 8, 12}
Resultyes
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 prices[] = {3, 3, 8, 12};
    int wanted = 3;
    size_t count = sizeof prices / sizeof prices[0];
    puts(bsearch(&wanted, prices, count, sizeof prices[0], compare) ? "yes" : "no");
    return 0;
}
Output
yes

Three appears in the sorted list. With duplicates, any matching element is sufficient for membership.

Advertisements

Check a badge at equipment pickup

The media desk releases cameras to students whose badge number is on the pickup list. Badge 204 is on the sheet between 101 and 305. The volunteer must match a whole number before handing out a camera.

GivenBadge 204 · pickup list 101, 204, 305
ResultRelease camera
lesson.c
#include <stdio.h>
#include <stdlib.h>

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

int main(void) {
    int badges[] = {101, 204, 305};
    int key = 204;
    const int *found = bsearch(&key, badges, 3, sizeof badges[0], compare_badges);
    puts(found ? "Release camera" : "Check roster");
    return 0;
}
Output
Release camera

The list contains badge 204, so the volunteer can release the camera. The recorded numbers identify students individually. bsearch requires the badge numbers to be sorted in the order used by its comparator.

Check an equipment loan

The school loans projectors to registered classrooms. A volunteer checks for a whole identifier before releasing equipment. Does the requested identifier occur in the list?

GivenRoom 16 in [12, 16, 21]
Worked resultListed

What to watch for

Sort by the same comparison rule that the lookup uses.

Documentation for bsearch