1 .\" Copyright 1993 David Metcalfe (david@prism.demon.co.uk)
3 .\" SPDX-License-Identifier: Linux-man-pages-copyleft
5 .\" References consulted:
6 .\" Linux libc source code
7 .\" Lewine's _POSIX Programmer's Guide_ (O'Reilly & Associates, 1991)
9 .\" Modified Mon Mar 29 22:41:16 1993, David Metcalfe
10 .\" Modified Sat Jul 24 21:35:16 1993, Rik Faith (faith@cs.unc.edu)
11 .TH BSEARCH 3 2021-08-27 GNU "Linux Programmer's Manual"
13 bsearch \- binary search of a sorted array
16 .RI ( libc ", " \-lc )
19 .B #include <stdlib.h>
21 .BI "void *bsearch(const void *" key ", const void *" base ,
22 .BI " size_t " nmemb ", size_t " size ,
23 .BI " int (*" compar ")(const void *, const void *));"
28 function searches an array of
31 the initial member of which is pointed to by
34 that matches the object pointed to by
36 The size of each member
37 of the array is specified by
40 The contents of the array should be in ascending sorted order according
41 to the comparison function referenced by
45 routine is expected to have two arguments which point to the
47 object and to an array member, in that order, and should return an integer
48 less than, equal to, or greater than zero if the
51 respectively, to be less than, to match, or be greater than the array
56 function returns a pointer to a matching member of the
57 array, or NULL if no match is found.
58 If there are multiple elements that
59 match the key, the element returned is unspecified.
61 For an explanation of the terms used in this section, see
69 Interface Attribute Value
72 T} Thread safety MT-Safe
78 POSIX.1-2001, POSIX.1-2008, C89, C99, SVr4, 4.3BSD.
80 The example below first sorts an array of structures using
82 then retrieves desired elements using
94 { 1, "jan" }, { 2, "feb" }, { 3, "mar" }, { 4, "apr" },
95 { 5, "may" }, { 6, "jun" }, { 7, "jul" }, { 8, "aug" },
96 { 9, "sep" }, {10, "oct" }, {11, "nov" }, {12, "dec" }
99 #define nr_of_months (sizeof(months)/sizeof(months[0]))
102 compmi(const void *m1, const void *m2)
104 const struct mi *mi1 = m1;
105 const struct mi *mi2 = m2;
106 return strcmp(mi1\->name, mi2\->name);
110 main(int argc, char *argv[])
112 qsort(months, nr_of_months, sizeof(months[0]), compmi);
113 for (int i = 1; i < argc; i++) {
118 res = bsearch(&key, months, nr_of_months,
119 sizeof(months[0]), compmi);
121 printf("\(aq%s\(aq: unknown month\en", argv[i]);
123 printf("%s: month #%d\en", res\->name, res\->nr);
128 .\" this example referred to in qsort.3