1bsearch(3) Library Functions Manual bsearch(3)
2
3
4
6 bsearch - binary search of a sorted array
7
9 Standard C library (libc, -lc)
10
12 #include <stdlib.h>
13
14 void *bsearch(const void key[.size], const void base[.size * .nmemb],
15 size_t nmemb, size_t size,
16 int (*compar)(const void [.size], const void [.size]));
17
19 The bsearch() function searches an array of nmemb objects, the initial
20 member of which is pointed to by base, for a member that matches the
21 object pointed to by key. The size of each member of the array is
22 specified by size.
23
24 The contents of the array should be in ascending sorted order according
25 to the comparison function referenced by compar. The compar routine is
26 expected to have two arguments which point to the key object and to an
27 array member, in that order, and should return an integer less than,
28 equal to, or greater than zero if the key object is found, respec‐
29 tively, to be less than, to match, or be greater than the array member.
30
32 The bsearch() function returns a pointer to a matching member of the
33 array, or NULL if no match is found. If there are multiple elements
34 that match the key, the element returned is unspecified.
35
37 For an explanation of the terms used in this section, see at‐
38 tributes(7).
39
40 ┌────────────────────────────────────────────┬───────────────┬─────────┐
41 │Interface │ Attribute │ Value │
42 ├────────────────────────────────────────────┼───────────────┼─────────┤
43 │bsearch() │ Thread safety │ MT-Safe │
44 └────────────────────────────────────────────┴───────────────┴─────────┘
45
47 C11, POSIX.1-2008.
48
50 POSIX.1-2001, C89, C99, SVr4, 4.3BSD.
51
53 The example below first sorts an array of structures using qsort(3),
54 then retrieves desired elements using bsearch().
55
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59
60 #define ARRAY_SIZE(arr) (sizeof((arr)) / sizeof((arr)[0]))
61
62 struct mi {
63 int nr;
64 const char *name;
65 };
66
67 static struct mi months[] = {
68 { 1, "jan" }, { 2, "feb" }, { 3, "mar" }, { 4, "apr" },
69 { 5, "may" }, { 6, "jun" }, { 7, "jul" }, { 8, "aug" },
70 { 9, "sep" }, {10, "oct" }, {11, "nov" }, {12, "dec" }
71 };
72
73 static int
74 compmi(const void *m1, const void *m2)
75 {
76 const struct mi *mi1 = m1;
77 const struct mi *mi2 = m2;
78
79 return strcmp(mi1->name, mi2->name);
80 }
81
82 int
83 main(int argc, char *argv[])
84 {
85 qsort(months, ARRAY_SIZE(months), sizeof(months[0]), compmi);
86 for (size_t i = 1; i < argc; i++) {
87 struct mi key;
88 struct mi *res;
89
90 key.name = argv[i];
91 res = bsearch(&key, months, ARRAY_SIZE(months),
92 sizeof(months[0]), compmi);
93 if (res == NULL)
94 printf("'%s': unknown month\n", argv[i]);
95 else
96 printf("%s: month #%d\n", res->name, res->nr);
97 }
98 exit(EXIT_SUCCESS);
99 }
100
102 hsearch(3), lsearch(3), qsort(3), tsearch(3)
103
104
105
106Linux man-pages 6.05 2023-07-20 bsearch(3)