5 /* Define an array of critters to sort. */
13 struct critter muppets
[] =
17 {"Gonzo", "whatever"},
22 {"Camilla", "chicken"},
23 {"Sweetums", "monster"},
24 {"Dr. Strangepork", "pig"},
25 {"Link Hogthrob", "pig"},
27 {"Dr. Bunsen Honeydew", "human"},
29 {"Swedish Chef", "human"}
32 int count
= sizeof (muppets
) / sizeof (struct critter
);
36 /* This is the comparison function used for sorting and searching. */
39 critter_cmp (const struct critter
*c1
, const struct critter
*c2
)
41 return strcmp (c1
->name
, c2
->name
);
45 /* Print information about a critter. */
48 print_critter (const struct critter
*c
)
50 printf ("%s, the %s\n", c
->name
, c
->species
);
55 /* Do the lookup into the sorted array. */
58 find_critter (const char *name
)
60 struct critter target
, *result
;
62 result
= bsearch (&target
, muppets
, count
, sizeof (struct critter
),
65 print_critter (result
);
67 printf ("Couldn't find %s.\n", name
);
78 for (i
= 0; i
< count
; i
++)
79 print_critter (&muppets
[i
]);
82 qsort (muppets
, count
, sizeof (struct critter
), critter_cmp
);
84 for (i
= 0; i
< count
; i
++)
85 print_critter (&muppets
[i
]);
88 find_critter ("Kermit");
89 find_critter ("Gonzo");
90 find_critter ("Janice");