I am trying to sort a dictionary in alphabetical order, which consists of structures with words followed by the meaning. When I run the program, the output for the third structure reads: <<arrow@, and the dictionary remains unsorted. I have tried a debugger but this doesnt seem to help. Thank you in advance.
/* program to sort a dictionary */
#include <stdio.h>
#include <string.h>
struct entry
{
char word [15];
char definition [50];
};
int compareString (char s1[], char s2[])
{
int i = 0;
int answer;
while (s1[i]== s2[i] && s1[i] != '\0' && s2[i] != '\0')
++i;
if (s1[i] < s2[i]) // s1 < s2
answer = -1;
else if (s1[i]== s2[i]) // s1 == s2
answer = 0;
else
answer =1; // s1 > s2
return answer;
}
void sortString (struct entry dictionary[], int entries)
{
int compareString (char s1[], char s2[]);
int i,j;
int result;
char temp[85];
char temp2[85];
for (i =0; i < entries; ++i)
{
for (j=i+1; j < entries; ++j)
result = compareString(dictionary[i].word, dictionary[j].word);
if (result < 0)
{
strcpy(temp, dictionary[i].word);
strcpy(temp2, dictionary[i].definition);
strcpy (dictionary[i].word, dictionary[j].word);
strcpy (dictionary [i].definition, dictionary[j].definition);
strcpy (dictionary[j].word, temp);
strcpy (dictionary[j].definition, temp2);
}
else
{
continue;
}
}
}
int main (void)
{
void sortString (struct entry dictionary[], int entries);
int k;
struct entry myDictionary [10] =
{ {"arrdvark", "a burrowing African mammal" },
{"aigrette", "an ornamental cluster of feathers"},
{"abyss", "a bottomless pit" },
{"acumen", "mentally sharp; keen" },
{"agar", "a jelly made from seaweed" },
{"addle", "to become confused" },
{"aerie", "a high nest" },
{"ahoy", "a nautical call of greeting" },
{"ajar", "partially opened" },
{"affix", "to append; attach" }};
sortString(myDictionary, 10);
for (k =0; k <10; ++k)
{
printf("%s means %s\n", myDictionary[k].word, myDictionary[k].definition);
}
return 0;
}
first to compare easily your strings you can use the function strcmp that is in string.h that you already include (take a look at man strcmp for more precision);
Secondary to sort your "dictionary" you can use the bubble sort algorithm which is a simple and adapted algorithm for your task : bubble sort algorithm, there is explanation and examples that can help you