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, size_t nmemb,
12 size_t size, int (*compar)(const void *, const void *));
13
15 The bsearch() function searches an array of nmemb objects, the initial
16 member of which is pointed to by base, for a member that matches the
17 object pointed to by key. The size of each member of the array is
18 specified by size.
19
20 The contents of the array should be in ascending sorted order according
21 to the comparison function referenced by compar. The compar routine is
22 expected to have two arguments which point to the key object and to an
23 array member, in that order, and should return an integer less than,
24 equal to, or greater than zero if the key object is found, respecā
25 tively, to be less than, to match, or be greater than the array member.
26
28 The bsearch() function returns a pointer to a matching member of the
29 array, or NULL if no match is found. If there are multiple elements
30 that match the key, the element returned is unspecified.
31
33 The example below first sorts an array of structures using qsort(3),
34 then retrieves desired elements using bsearch().
35
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39
40 struct mi {
41 int nr;
42 char *name;
43 } months[] = {
44 { 1, "jan" }, { 2, "feb" }, { 3, "mar" }, { 4, "apr" },
45 { 5, "may" }, { 6, "jun" }, { 7, "jul" }, { 8, "aug" },
46 { 9, "sep" }, {10, "oct" }, {11, "nov" }, {12, "dec" }
47 };
48
49 #define nr_of_months (sizeof(months)/sizeof(months[0]))
50
51 static int compmi(const void *m1, const void *m2) {
52 struct mi *mi1 = (struct mi *) m1;
53 struct mi *mi2 = (struct mi *) m2;
54 return strcmp(mi1->name, mi2->name);
55 }
56
57 int main(int argc, char **argv) {
58 int i;
59
60 qsort(months, nr_of_months, sizeof(struct mi), compmi);
61 for (i = 1; i < argc; i++) {
62 struct mi key, *res;
63 key.name = argv[i];
64 res = bsearch(&key, months, nr_of_months,
65 sizeof(struct mi), compmi);
66 if (res == NULL)
67 printf("'%s': unknown month\n", argv[i]);
68 else
69 printf("%s: month #%d\n", res->name, res->nr);
70 }
71 return 0;
72 }
73
75 SVr4, 4.3BSD, POSIX.1-2001, C89, C99
76
78 hsearch(3), lsearch(3), qsort(3), tsearch(3)
79
80
81
82 2003-11-01 BSEARCH(3)