3

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

austin robinson
  • 51
  • 1
  • 1
  • 6
  • 2
    You should probably do a little research on sorting algorithms, the only difference between sorting a list of numbers and sorting a list of words alphabetically is the comparison method, which is fairly easy to do – Dan F Aug 23 '13 at 17:31
  • 2
    Take a step back, go enjoy a nice cup of tea or something. When you come back to this, take it one step at a time. First get that array populated, then you can worry about sorting. – Dennis Meng Aug 23 '13 at 17:32
  • 4
    http://en.wikipedia.org/wiki/Bubble_sort – Oscar Aug 23 '13 at 17:32
  • The easiest solution that comes to mind is just implementing a [QuickSort](http://en.wikipedia.org/wiki/Quicksort) and using strcmp in your partitioning code (-1 for the less-than side, >=0 for the equal-to/greater-than side) – George Mitchell Aug 23 '13 at 17:35
  • @Oscar, Lol for the bubble sort suggestion. XD – Jordan Aug 23 '13 at 17:38
  • 3
    @GeorgeMitchell 1) Quicksort on 4 elements? 2) Given that the poster is relatively new to programming, it might be better if he does bubble/insertion/selection sort, just to be able to code the logic. – Dennis Meng Aug 23 '13 at 17:39
  • 2
    @GeorgeMitchell quicksort is probably *not* the easiest solution for a beginner. I would recommend starting with a physical analogy - if I give you a stack of baseball cards or something, and tell you to sort them, how would you do it? It's a rare person that would come up with quicksort. I suspect the majority of people would essentially start with an insertion or selection sort. – twalberg Aug 23 '13 at 17:43
  • It must be really challenging to reinvent the wheel for someone who has never seen a wheel. – jaeheung Aug 23 '13 at 17:43
  • @DennisMeng ... Oops! For some reason my brain skipped the [4] part. I was thinking something more like ~[50]ish! :) ... 2.) But who doesn't **love** recursion??? – George Mitchell Aug 23 '13 at 17:45
  • @GeorgeMitchell As an ex-algorithms TA, I like recursion more than most, but there's no need to overcomplicate things for someone who's just trying to get the basics. – Dennis Meng Aug 23 '13 at 17:49
  • What book is this "straight from"? Inquiring minds want to know. – verbose Aug 23 '13 at 19:07

6 Answers6

6

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

pm100
  • 48,078
  • 23
  • 82
  • 145
5

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.

Community
  • 1
  • 1
user1231232141214124
  • 1,339
  • 3
  • 16
  • 22
4

Do you need "any" sorting algorithm, or an "efficient" sorting algorithm?

For simplicity, I can show you how to implement an easy, but not efficient, sorting algorithm. It's the double for method!! Then, with the same ideas, you can modify it to any other efficient algorithm (like shell, or quicksort).

For numbers, you could put arrays ir order, as follows (as you probably know):

int intcmp(int a, int b) {
    return (a < b)? -1: ((a > b)? +1: 0);
}

int main(void) {
   int a[5] = {3, 4, 22, -13, 9};

   for (int i = 0; i < 5; i++) {
      for (int j = i+1; j < 5; j++)
         if (intcmp(a[i], a[j]) > 0) {
            int temp = a[i]; 
            a[i] = a[j]; 
            a[j] = temp; 
         }
       printf("%d ", a[i]);
   }
}

The only thing that has changed now is that you have strings intead integers. So, you have to consider an array of strings:

 char *a[] = {"Florida", "Oregon", "Califoria", "Georgia"};

Then, you have to change the type of temp to char*,
and finally you put the function strcmp() instead of intcmp().

The function strcmp(s1, s2) (from < string.h >) returns a number < 0 if s1 is a string "less than" s2, == 0 if s1 is "equal to" s2, and > 1 else.

The program looks like this:

#include <stdio.h>
#include <string.h>
int main(void) {
   char *a[] = {"Florida", "Oregon", "Califoria", "Georgia"};

   for (int i = 0; i < 4; i++) {
      for (int j = i+1; j < 4; j++)
         if (strcmp(a[i], a[j]) > 0) {
            char* temp = a[i]; 
            a[i] = a[j]; 
            a[j] = temp; 
         }
       printf("%s ", a[i]);
     }
   getchar();
   return 0;  
}

Note that for the printf() sentence, we have changed "%d " by "%s ", in order to properly show strings.

Final comment: When you program a better algorithm, like quick-sort, it is enough that you change the comparisson function, because the algorithm it is the same, in despite of the type of data you are comparing.

Remark: I have used a "tricky" method. As you can see, I have defined the variable a as a pointer to string. The initializer has taken a constant array of strings and then initialized the variable a with it. The variable a now can be safely treated and indexed as an array of exactly 4 pointer-to-strings.
That is the reason why the "swap" works fine in the double-for algorithm: The memory addresses are swapped instead the entire strings.

pablo1977
  • 4,281
  • 1
  • 15
  • 41
3

Steps you likely should take:

  1. Populate array with state names
  2. Create method to swap two states in place in the array
  3. At this point you have all the tools necessary to use strcmp to implement any sorting algorithm you choose

Most sorting methods rely on two things.

  1. Being able to rearrange a list (i.e. swap)
  2. Being able to compare items in list to see if they should be swapped

I would work on getting those two things working correctly and the rest should just be learning a particular sorting algorithm

spartacus
  • 613
  • 6
  • 12
1

Beware of a little headaching problem: Strings are sorted by ascii numeric representations, so if you sort alphabetically like this, any capital letter will come before a lowercase letter e.g. "alpha", "beta", "gamma", "Theta" will be sorted as: Theta, alpha, beta, gamma

0

When it comes to the sample array you have listed here the simple algorithm mentioned earlier might actually be the most efficient. The algorithm I'm referring to is the one where you start with the first element and then compare it to the others and substitute with the smallest you find and then going to the next element to do the same only dont compare it to the already sorted elements.

While this algorithm has an execution time of O(n^2). Where n is the number of elements in the array. It will usually be faster than something like quick sort (execution time O(n*log(n)) for smaller arrays. The reason being that quick sort has more overhead. For larger arrays quick sort will serve you better than the other method, which if memory serves me right is called substitution sort although I see it mentioned as "double for" in a different answer.

ElvishPriestley
  • 45
  • 1
  • 1
  • 8