/* Program 10-10

   Dictionary lookup with binary search */

struct entry
 {
  char word[10];
  char definition[50];
 };

/* Function to compare two character strings */

int compare_strings (char s1[], char s2[])
 {
  int i = 0, answer;

  while ( s1[i] == s2[i]  &&  s1[i] != '\0'  &&  s2[i] != '\0' )
   ++i;

  if ( s1[i] < s2[i] )
   answer = -1;
  else if ( s1[i] == s2[i] )
   answer = 0;
  else
   answer = 1;

  return (answer);
 }

/* Function to lookup a word inside a dictionary */

int lookup (struct entry dictionary[], char search[], int number_of_entries)
 {
  int low = 0;
  int high = number_of_entries - 1;
  int mid, result;

  while ( low <= high )
   {
    mid = (low + high) / 2;
    result = compare_strings (dictionary[mid].word, search);

    if ( result == -1 )
     low = mid + 1;
    else if ( result == 1 )
     high = mid - 1;
    else
     return (mid);
   }
  return (-1);
 }

main ()
 {
  static struct entry dictionary[10] =
   { { "aardvark", "a burrowing African mammal"        },
     { "abyss",    "a bottomless pit"                  },
     { "acumen",   "mentally sharp; keen"              },
     { "addle",    "to become confused"                },
     { "aerie",    "a high nest"                       },
     { "affix",    "to append; attach"                 },
     { "agar",     "a jelly made from seaweed"         },
     { "ahoy",     "a nautical call of greeting"       },
     { "aigrette", "an ornamental cluster of feathers" },
     { "ajar",     "partially opened"                  } };

  int  entries = 10;
  char word[10];
  int  entry_number;

  printf ("Enter word:\n");
  scanf ("%s", word);

  entry_number = lookup (dictionary, word, entries);

  if ( entry_number != -1 )
   printf ("%s\n", dictionary[entry_number].definition);
  else
   printf ("Sorry, that word is not in my dictionary.\n");
 }


/* Program Output

Enter word:
aigrette
an ornamental cluster of feathers

*/

