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