bsearch in C: solved exercise on sorted array

bsearch in C: solved exercise on sorted array

This exercise is scheduled for daily publication and follows the same didactic structure used across the site: clear statement, compilable code, and expected output.

Problem statement

Implement a practical example of the topic and validate the output in the console.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
#include <stdlib.h>

int cmp_int(const void *a, const void *b) {
    int x = *(const int *)a;
    int y = *(const int *)b;
    return (x > y) - (x < y);
}

int main(void) {
    int v[] = {1, 3, 5, 7, 9, 11};
    int n = (int)(sizeof(v) / sizeof(v[0]));
    int clave = 7;

    int *p = bsearch(&clave, v, n, sizeof(int), cmp_int);
    if (p) printf("Encontrado: %d\n", *p);
    else printf("No encontrado\n");
    return 0;
}

Expected output

1
Encontrado: 7

Common mistakes

  • Not validating input and standard-library return values.
  • Ignoring edge cases (buffers, limits, null pointers).
  • Skipping basic compile/run verification.

Practical use

The C standard library bsearch is useful when the array is already sorted and efficient search is needed without implementing the algorithm.

Guided practice and full book

If you want a complete path with progressive difficulty:

FAQ

Is this exercise useful for C exams and technical interviews?

Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.

Where can I keep practicing with more solved C exercises?

In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.

How should I practice this exercise type to improve faster?

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.