1 /* Searching and Sorting Example
2 Copyright (C) 1991-2020 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, see <https://www.gnu.org/licenses/>.
22 /* Define an array of critters to sort. */
30 struct critter muppets
[] =
34 {"Gonzo", "whatever"},
39 {"Camilla", "chicken"},
40 {"Sweetums", "monster"},
41 {"Dr. Strangepork", "pig"},
42 {"Link Hogthrob", "pig"},
44 {"Dr. Bunsen Honeydew", "human"},
46 {"Swedish Chef", "human"}
49 int count
= sizeof (muppets
) / sizeof (struct critter
);
53 /* This is the comparison function used for sorting and searching. */
56 critter_cmp (const void *v1
, const void *v2
)
58 const struct critter
*c1
= v1
;
59 const struct critter
*c2
= v2
;
61 return strcmp (c1
->name
, c2
->name
);
65 /* Print information about a critter. */
68 print_critter (const struct critter
*c
)
70 printf ("%s, the %s\n", c
->name
, c
->species
);
75 /* Do the lookup into the sorted array. */
78 find_critter (const char *name
)
80 struct critter target
, *result
;
82 result
= bsearch (&target
, muppets
, count
, sizeof (struct critter
),
85 print_critter (result
);
87 printf ("Couldn't find %s.\n", name
);
98 for (i
= 0; i
< count
; i
++)
99 print_critter (&muppets
[i
]);
102 qsort (muppets
, count
, sizeof (struct critter
), critter_cmp
);
104 for (i
= 0; i
< count
; i
++)
105 print_critter (&muppets
[i
]);
108 find_critter ("Kermit");
109 find_critter ("Gonzo");
110 find_critter ("Janice");