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 SVr4, 4.3BSD, POSIX.1-2001, C89, C99.
35
37 The example below first sorts an array of structures using qsort(3),
38 then retrieves desired elements using bsearch().
39
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43
44 struct mi {
45 int nr;
46 char *name;
47 } months[] = {
48 { 1, "jan" }, { 2, "feb" }, { 3, "mar" }, { 4, "apr" },
49 { 5, "may" }, { 6, "jun" }, { 7, "jul" }, { 8, "aug" },
50 { 9, "sep" }, {10, "oct" }, {11, "nov" }, {12, "dec" }
51 };
52
53 #define nr_of_months (sizeof(months)/sizeof(months[0]))
54
55 static int
56 compmi(const void *m1, const void *m2)
57 {
58 struct mi *mi1 = (struct mi *) m1;
59 struct mi *mi2 = (struct mi *) m2;
60 return strcmp(mi1->name, mi2->name);
61 }
62
63 int
64 main(int argc, char **argv)
65 {
66 int i;
67
68 qsort(months, nr_of_months, sizeof(struct mi), compmi);
69 for (i = 1; i < argc; i++) {
70 struct mi key, *res;
71 key.name = argv[i];
72 res = bsearch(&key, months, nr_of_months,
73 sizeof(struct mi), compmi);
74 if (res == NULL)
75 printf("'%s': unknown month\n", argv[i]);
76 else
77 printf("%s: month #%d\n", res->name, res->nr);
78 }
79 exit(EXIT_SUCCESS);
80 }
81
83 hsearch(3), lsearch(3), qsort(3), tsearch(3)
84
86 This page is part of release 3.25 of the Linux man-pages project. A
87 description of the project, and information about reporting bugs, can
88 be found at http://www.kernel.org/doc/man-pages/.
89
90
91
92 2003-11-01 BSEARCH(3)