Search code examples
calgorithmsortingstrcmp

Logic challenge: sorting arrays alphabetically in C


I'm new to programming, currently learning C. I've been working at this problem for a week now, and I just can't seem to get the logic straight. This is straight from the book I'm using:

Build a program that uses an array of strings to store the following names:

  • "Florida"
  • "Oregon"
  • "Califoria"
  • "Georgia"

Using the preceding array of strings, write your own sort() function to display each state's name in alphabetical order using the strcmp() function.

So, let's say I have:

char *statesArray[4] = {"Florida", "Oregon", "California", "Georgia"}; 

Should I do nested for loops, like strcmp(string[x], string[y])...? I've hacked and hacked away. I just can't wrap my head around the algorithm required to solve this even somewhat efficiently. Help MUCH appreciated!!!


Solution

  • Yes, you can sort by using nested for loops. After you understand how strcmp() works it should be fairly straight forward:

    strcmp(char *string1, char *string2)

    • if Return value is < 0 then it indicates string1 is less than string2

    • if Return value is > 0 then it indicates string2 is less than string1

    • if Return value is = 0 then it indicates string1 is equal to string2

    You can then choose any of the sorting methods once from this point

    This site has a ton of great graphical examples of various sorts being performed and includes the pseudo code for the given algorithms.