Δυαδική αναζήτηση

Παράδειγμα

Το παρακάτω παράδειγμα διαβάζει μια γραμμή και την τυπώνει σύμφωνα με το διεθνές φωνητικό αλφάβητο (π.χ. για τη γραμμή HELLO WORLD θα τυπώσει:
Hotel
Echo
Lima
Lima
Oscar
Whiskey
Oscar
Romeo
Lima
Delta
/*
 * Read a line from the standard input and print it according to the
 * international phonetic alphabet.
 *
 * Diomidis Spinellis.  March 1999.
 *
 * $Id$
 *
 */

#include <stdlib.h>
#include <stdio.h>

/*
 * The international phonetic alphabet (sorted)
 */
char *names[] = {
	"Alpha",
	"Bravo",
	"Charlie",
	"Delta",
	"Echo",
	"Foxtrot",
	"Golf",
	"Hotel",
	"India",
	"Juliet",
	"Kilo",
	"Lima",
	"Mike",
	"November",
	"Oscar",
	"Papa",
	"Quebec",
	"Romeo",
	"Sierra",
	"Tango",
	"Uniform",
	"Victor",
	"Whiskey",
	"X-Ray",
	"Yankee",
	"Zulu",
};

/*
 * Bsearch compare function
 */
static int
namecmp(char **a, char **b)
{
	return (**a - **b);
}

main()
{
	char buff[80], *p, **name;

	fgets(buff, sizeof(buff), stdin);
	for (p = buff; *p; p++)
		if (name = (char **)bsearch(&p, names, 26, sizeof(char *), namecmp))
			printf("%s\n", *name, *name);
}