Logic challenge: sorting arrays alphabetically in C

algorithmcsortingstrcmp

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!!!

Best Answer

imagine you had to sort the array - think of each state written on a card. HOw would you sort it into order. There are many ways of doing it. Each one is called an algorithm

One way is to find the first state by looking at every card and keeping track in your head of the lowest one you have seen. After looking at each card you will have the lowest one. Put that in a new pile. NOw repeat - trying to find the lowest of the ones you have left.

repeat till no cards left in original pile

This is a well known simple but slow algorithm. Its the one i would do first

there are other ones too