Programming in C

(Barry) #1

224 Chapter 10 Character Strings


Now that you have the algorithm for performing a binary search, you can rewrite
your lookupfunction to use this new search strategy. Because the binary search must be
able to determine if one value is less than, greater than, or equal to another value, you
might want to replace your equalStringsfunction with another function that makes
this type of determination for two character strings. Call the function compareStrings
and have it return the value – 1 if the first string is lexicographically less than the second
string, 0 if the two strings are equal, and 1 if the first string is lexicographically greater
than the second string. So, the function call
compareStrings ("alpha", "altered")
returns the value – 1 because the first string is lexicographically less than the second
string (think of this to mean that the first string occurs beforethe second string in a dic-
tionary). And, the function call
compareStrings ("zioty", "yucca");
returns the value 1 because “zioty” is lexicographically greater than “yucca.”
In Program 10.10, the new compareStringsfunction is presented.The lookupfunc-
tion now uses the binary search method to scan through the dictionary.The mainrou-
tine remains unchanged from the previous program.

Program 10.10 Modifying the Dictionary Lookup Using Binary Search
// Dictionary lookup program

#include <stdio.h>

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

// Function to compare two character strings

int compareStrings (const char s1[], const 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; /* s1 < s2 */
else if ( s1[i] == s2[i] )
answer = 0; /* s1 == s2 */
Free download pdf