#include "library.h" const string animals[] = { "aardvark", "albatross", "alligator", "amoeba", "ant", "anteater", "antelope", "armadillo", "baboon", "bat", "bear", "bee", "beetle", "butterfly", "caprimulgus", "caribou", "carp", "cat", "caterpillar", "chicken", "chimpanzee", "cod", "cougar", "cow", "crab", "crocodile", "deer", "dingo", "dog", "dolphin", "dove", "duck", "eagle", "eel", "elephant", "elk", "ferret", "flamingo", "flounder", "frog", "gerbil", "giraffe", "gnu", "goat", "goldfish", "gorilla", "haddock", "hamster", "hawk", "hedgehog", "hen", "hippopotamus", "hyaena", "iguana", "jackass", "kangaroo", "koala", "lamprey", "lemur", "leopard", "lion", "llama", "lobster", "monkey", "moose", "mosquito", "moth", "mouse", "nematode", "newt", "octopus", "opossum", "orangutan", "osprey", "otter", "owl", "panda", "panther", "peacock", "penguin", "pheasant", "pigeon", "pig", "porcupine", "prairie-dog", "quagga", "quail", "rabbit", "racoon", "rat", "rhinoceros", "salamander", "sea-urchin", "seahorse", "seal", "sealion", "semicolon", "shark", "shrimp", "skunk", "snake", "sphynx", "spider", "squid", "squirrel", "starfish", "tapeworm", "tiger", "tortoise", "tuna", "turkey", "turtle", "unicorn", "varmint", "vole", "vulture", "walrus", "warthog", "weasel", "weevil", "whale", "woodlouse", "woodpecker", "worm", "yeti", "zebra", "zebu" }; int find(const string q, const int minpos, const int maxpos) { if (minpos > maxpos) return -1; const int midpos = (minpos + maxpos) / 2; const string seeing = animals[midpos]; // obviously this cout would not be in a production version. cout << "min = " << minpos << ", max = " << maxpos << ", range = " << maxpos - minpos + 1 << ", mid = " << midpos << ", seeing \"" << seeing << "\"\n"; if (q == seeing) return midpos; else if (q < seeing) return find(q, minpos, midpos - 1); else return find(q, midpos + 1, maxpos); } int find(const string q) { const int N = sizeof(animals) / sizeof(string); return find(q, 0, N - 1); } int main() { while (true) { cout << "animal? "; const string x = read_string(); const int pos = find(x); if (pos < 0) cout << "\"" << x << "\" not found\n"; else cout << "\"" << animals[pos] << "\" is at position " << pos << "\n"; } }