20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

224 Chapter 10 Character Str<strong>in</strong>gs<br />

Now that you have the algorithm for perform<strong>in</strong>g a b<strong>in</strong>ary search, you can rewrite<br />

your lookup function to use this new search strategy. Because the b<strong>in</strong>ary search must be<br />

able to determ<strong>in</strong>e if one value is less than, greater than, or equal to another value, you<br />

might want to replace your equalStr<strong>in</strong>gs function with another function that makes<br />

this type of determ<strong>in</strong>ation for two character str<strong>in</strong>gs. Call the function compareStr<strong>in</strong>gs<br />

and have it return the value –1 if the first str<strong>in</strong>g is lexicographically less than the second<br />

str<strong>in</strong>g, 0 if the two str<strong>in</strong>gs are equal, and 1 if the first str<strong>in</strong>g is lexicographically greater<br />

than the second str<strong>in</strong>g. So, the function call<br />

compareStr<strong>in</strong>gs ("alpha", "altered")<br />

returns the value –1 because the first str<strong>in</strong>g is lexicographically less than the second<br />

str<strong>in</strong>g (th<strong>in</strong>k of this to mean that the first str<strong>in</strong>g occurs before the second str<strong>in</strong>g <strong>in</strong> a dictionary).<br />

And, the function call<br />

compareStr<strong>in</strong>gs ("zioty", "yucca");<br />

returns the value 1 because “zioty” is lexicographically greater than “yucca.”<br />

In Program 10.10, the new compareStr<strong>in</strong>gs function is presented.The lookup function<br />

now uses the b<strong>in</strong>ary search method to scan through the dictionary.The ma<strong>in</strong> rout<strong>in</strong>e<br />

rema<strong>in</strong>s unchanged from the previous program.<br />

Program 10.10 Modify<strong>in</strong>g the Dictionary Lookup Us<strong>in</strong>g B<strong>in</strong>ary Search<br />

// Dictionary lookup program<br />

#<strong>in</strong>clude <br />

struct entry<br />

{<br />

char word[15];<br />

char def<strong>in</strong>ition[50];<br />

};<br />

// Function to compare two character str<strong>in</strong>gs<br />

<strong>in</strong>t compareStr<strong>in</strong>gs (const char s1[], const char s2[])<br />

{<br />

<strong>in</strong>t i = 0, answer;<br />

while ( s1[i] == s2[i] && s1[i] != '\0'&& s2[i] != '\0' )<br />

++i;<br />

if ( s1[i] < s2[i] )<br />

answer = -1; /* s1 < s2 */<br />

else if ( s1[i] == s2[i] )<br />

answer = 0; /* s1 == s2 */

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!