I am trying to sort strings in an array of structures alphabetically then print, but my code doesn't work.
I've been trying to figure out why for the past few hours, but can't figure it out. I'm sure its probably something super obvious, but I've only been programming for a few weeks and I can't figure it out.
It does compile with no errors, the output is just a print of the original unsorted array but without aardvark, like so: boy acumen addle cat affix agar ahoy aigrette ajar
Here is my code so far:
#include <stdio.h>
struct entry
{
char word[15];
char definition[50];
};
struct entry dictionary[100] =
{ {"boy", "a boy " },
{"aardvark", "a burrowing African mammal" },
{"acumen", "mentally sharp; keen" },
{"addle", "to become confused" },
{"cat", "a cat" },
{"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 main(void)
{
int i;
void dictionarySort(struct entry dictionary[]);
dictionarySort(dictionary);
for(i = 0; i < 10; ++i)
{
printf("%s\n", dictionary[i].word);
}
return 0;
}
void dictionarySort(struct entry dictionary[])
{
int i, k, j;
struct entry temp[100];
for(i = 0; i <= 9; ++i)
{
for( k = 0; dictionary[i].word[k] != '\0'; ++k)
{
if( (dictionary[i].word[k] > dictionary[i+1].word[k] ) )
{
temp[i] = dictionary[i];
dictionary[i] = dictionary[i+1];
dictionary[i+1] = temp[i];
}
}
}
}
If anyone has any input I would appreciate it.
First of all, the algorithm you are trying to build is not sorting. What you have here is (after fixing issues described below) one iteration of bubble sort. To make it actually sort the array you need to call
dictioarySort
10 times. See https://en.wikipedia.org/wiki/Bubble_sort for more details.Now to the other issues in the code. You can simplify your entire loop by just using
strcmp
:But if you are making some kind of an exercise and want to figure out how to do it your way, there are two issues with your logic:
Consider words "azc" and "brc". They are in alphabetical order, so they don't need to be swapped. After you look at their first characters,
a
andb
correspondingly, you should stop comparing them. Instead you continue to the next letter,z
andr
correspondingly, and decide to swap them based on that, leading to an incorrect order.After you swap two words, you should also stop. Consider a case of
za
,rb
. After looking at the first letters,z
andr
, you will swap the words (which is good). But then you will look at the second letters. This time the words are already swapped, so you will look atb
anda
, and swap them again. So the full solution will be along the lines of: