C Fundamentals
Algorithms · data structures · cryptography · systems — pure C11, zero deps
Loading...
Searching...
No Matches
binary_search.h
Go to the documentation of this file.
1/**
2 * @file binary_search.h
3 * @brief Binary search on sorted arrays. O(log n) time, O(1) space.
4 *
5 * Returns the index of the target if found, or `(size_t)-1` if not.
6 * The input array MUST be sorted in ascending order — the caller's
7 * responsibility, not checked here.
8 */
9
10#ifndef BINARY_SEARCH_H
11#define BINARY_SEARCH_H
12
13#include <stddef.h>
14
15#define BSEARCH_NOT_FOUND ((size_t)-1)
16
17size_t binary_search_ints(const int *arr, size_t n, int target);
18size_t binary_search_strings(const char *const *arr, size_t n, const char *target);
19
20/* Recursive variant for the curious — same complexity, used in tests. */
21size_t binary_search_ints_recursive(const int *arr, size_t lo, size_t hi, int target);
22
23#endif /* BINARY_SEARCH_H */
size_t binary_search_strings(const char *const *arr, size_t n, const char *target)
size_t binary_search_ints_recursive(const int *arr, size_t lo, size_t hi, int target)
size_t binary_search_ints(const int *arr, size_t n, int target)