codex
Loading...
Searching...
No Matches
bsearch.h
Go to the documentation of this file.
1#include <stdbool.h>
2#include <stddef.h>
3#include <stdio.h>
4
5bool lsearch(int x, const int *p, const int *e) {
6 assert(p <= e);
7 for(; p != e; ++p)
8 if(x == *p)
9 return true;
10 return false;
11}
12
13static inline const int *bsearch_middle(const int *p, const int *e) {
14 assert(p <= e);
15 return p + ((e - p) >> 1);
16}
17
18bool bsearch0(int x, const int *p, const int *e) {
19 const ptrdiff_t n = e - p;
20 if(n <= 0)
21 return false;
22 const int *m = bsearch_middle(p, e);
23 if(m == p)
24 return *m == x;
25 if(x < *m)
26 return bsearch0(x, p, m);
27 if(*m < x)
28 return bsearch0(x, m + 1, e);
29 return true;
30}
31
32bool bsearch1(int x, const int *p, const int *e) {
33 while(p != e) {
34 const int *m = bsearch_middle(p, e);
35 if(m == p)
36 return *m == x;
37 if(x < *m)
38 e = m;
39 else if(*m < x)
40 p = m + 1;
41 else
42 return true;
43 }
44 return false;
45}
46
47bool bsearch2(int x, const int *p, const int *e) {
48 while(p != e) {
49 const int *m = bsearch_middle(p, e);
50 if(*m < x)
51 p = m + 1;
52 else if(x < *m)
53 e = m;
54 else
55 return true;
56 }
57 return false;
58}
59
60const int *lower_bound(int x, const int *p, const int *ie) {
61 for(const int *e = ie; p != e;) {
62 const int *m = bsearch_middle(p, e);
63 if(*m < x)
64 p = m + 1;
65 else
66 e = m;
67 }
68 return p;
69}
70
71bool bsearch3(int x, const int *p, const int *e) {
72 p = lower_bound(x, p, e);
73 return p != e && !(x < *p);
74}
bool bsearch2(int x, const int *p, const int *e)
Definition bsearch.h:47
bool bsearch1(int x, const int *p, const int *e)
Definition bsearch.h:32
bool bsearch3(int x, const int *p, const int *e)
Definition bsearch.h:71
const int * lower_bound(int x, const int *p, const int *ie)
Definition bsearch.h:60
bool bsearch0(int x, const int *p, const int *e)
Definition bsearch.h:18
static const int * bsearch_middle(const int *p, const int *e)
Definition bsearch.h:13
bool lsearch(int x, const int *p, const int *e)
Definition bsearch.h:5
#define x
Definition gcc14.c:1
#define m(a)
Definition std2.c:8
#define p()
Definition std2.c:11