Thread: Alphabetical sorting in a character array?

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    4

    Alphabetical sorting in a character array?

    Hi, I'm working on a little program, both for school and just to get better with C, which is supposed to do the following:
    • Accept a string input by a user
    • Store the string in a character array
    • Print out user's string
    • Reverse the order of words in user's string (this is an example string = string example an is this)
    • Print out the new string
    • Sort the letters in each word in alphabetical order (example = aeelmpx)
    • Print out the new string

    I've done most of my coding using C++ and C# so on top of dealing with the slightly different syntax of C, I've run into a problem on the final two steps, the alphabetical sorting.

    So far, this is the code I have:
    Code:
    // Function to reverse the entire string
    void reverseString(char *start, char *end)
    {
        // Initialize temporary variable
        char temp;
    
        while (start < end)
        {
            temp = *start;
            *start++ = *end;
            *end-- = temp;
        }
    }
    
    void main (void)
    {
        // Initialize variables
        char string[30];
        char *end, *x, *y;
    
        while (1)
        {
            printf("Enter a string: ");
            gets(string, 30);
            printf("Your string: %s", string);
    
            // Find end of the string
            for(end = string; *end; end++);
    
            // Reverse the entire string
            reverseString(string, end-1);
    
            // Create new start and end points
            x = string-1;
            y = string;
    
            // Until the end of the string is reached
            while(x++ < end)
            {
                // Reverse each word
                if(*x == '\0' || *x == ' ')
                {
                    reverseString(y, x-1);
                    y = x+1;
                }
            }
    
            printf("\nYour reversed string: %s\n\n", string);
        }
    }
    To clarify some things beforehand, I'll explain some things that I think might be questioned. First, I use void main() instead of int main() because we're supposed to have the program run indefinitely until it's manually shut down so I do not want to return 0 to shut off the program as I would normally. Second, I know scanf() is better than gets() (or at least, I think it is if my research was right) but we're also required to meet a specific size for the code file and whenever I use scanf(), the size of the file comes dangerously close to our limit. Finally, everything up to this point works fine so unless you see something that is horribly wrong, it's not my primary concern to change any of the code that I already have.

    With that out of the way, I want to ask if anyone can point me in the right direction as to how to go about sorting the letters of each word in alphabetical order. I know I can use the same while loop to split the string into separate words but I'm just at a complete loss as to how to code the function to sort the letters alphabetically. I don't just want the code either but rather, an explanation as to how to do it first and if I can't figure it out, I'll come back. If anyone can help me out, I'd greatly appreciate it.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by YPavluk View Post
    To clarify some things beforehand, I'll explain some things that I think might be questioned. First, I use void main() instead of int main() because we're supposed to have the program run indefinitely until it's manually shut down so I do not want to return 0 to shut off the program as I would normally.
    That doesn't even begin to make sense.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by YPavluk
    First, I use void main() instead of int main() because we're supposed to have the program run indefinitely until it's manually shut down so I do not want to return 0 to shut off the program as I would normally.
    Just use the standard form. If the line is unreachable, so be it. (Plus it does not have to be unreachable since you can write the program to terminate the main loop on EOF.)

    Quote Originally Posted by YPavluk
    I know scanf() is better than gets() (or at least, I think it is if my research was right) but we're also required to meet a specific size for the code file and whenever I use scanf(), the size of the file comes dangerously close to our limit.
    The size of the resulting executable? That would not make sense unless you are doing embedded programming, but it does not look like you are. Anyway, use fgets, not gets.

    Quote Originally Posted by YPavluk
    how to go about sorting the letters of each word in alphabetical order
    A simple way is to use qsort from <stdlib.h> with a comparison function.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User
    Join Date
    Oct 2011
    Posts
    4
    What about it doesn't make sense? Rather than having "return 0;" at the end of the program, causing it to shut down once all of the code has been run through, the program returns back to the beginning, asking for the user to input a new string, over and over again, until the user decides to shut it down. If that still doesn't make sense, I don't really know how to make it any clearer but either way, that doesn't really relate to my problem as I mentioned in my first post, the program is fully functional at this point sans the alphabetical sorting.

  5. #5
    Registered User
    Join Date
    Oct 2011
    Posts
    4
    I am using embedded programming. I took some of the code out (just as I did in order to run it using a different compiler) but as I mentioned, that stuff is not really a big concern and it's something I can work on later, once the alphabetical sorting has been worked out. I haven't ever used qsort before (haven't had a need to really) so is it possible for you to explain that a little bit more? If not, I'll go ahead and Google it but I'm just guessing it would be much easier to understand if you were able to apply it to my situation specifically rather than just random pieces of code I find on the Internet.

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    People post questions on sorting all the time. Just look down the page. Someone is bound to be sorting. Do a boboli sort.


    Quzah.
    Hope is the first step on the road to disappointment.

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by YPavluk
    I am using embedded programming.
    Oh, in that case, I don't think it is guaranteed that qsort will be available for use. But assuming it is...

    Quote Originally Posted by YPavluk
    I haven't ever used qsort before (haven't had a need to really) so is it possible for you to explain that a little bit more? If not, I'll go ahead and Google it but I'm just guessing it would be much easier to understand if you were able to apply it to my situation specifically rather than just random pieces of code I find on the Internet.
    Search the Web first. The basic idea is to sort the string as an array of char, excluding the null character, by providing qsort with a comparison function that compares two char passed in via pointers to void.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #8
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by YPavluk View Post
    What about it doesn't make sense? Rather than having "return 0;" at the end of the program, causing it to shut down once all of the code has been run through, the program returns back to the beginning, asking for the user to input a new string, over and over again, until the user decides to shut it down. If that still doesn't make sense, I don't really know how to make it any clearer but either way, that doesn't really relate to my problem as I mentioned in my first post, the program is fully functional at this point sans the alphabetical sorting.
    Ummm... no. The return value from a process is not a shutdown code, and it's silly to think it is. In fact, it represents a fundimental misunderstanding of how C programming works.

    It's the loop that keeps your program running not the absence of a return value.

    Operating Systems *expect* an integer return value, which generally represents an errorlevel... we return 0 to say "no errors"... void main() is a hang over from a wildly outdated, non-standard (even then) compiler that seems not to want to die. You should always use the correct form of ...
    Code:
    int main (void)
      {
         // your code
    
         return 0;  // or an error code
    }
    If you want your program to keep running, make sure the final return statement is outside your loop.

  9. #9
    Registered User
    Join Date
    Oct 2011
    Posts
    4
    Quote Originally Posted by CommonTater View Post
    Ummm... no. The return value from a process is not a shutdown code, and it's silly to think it is. In fact, it represents a fundimental misunderstanding of how C programming works.

    It's the loop that keeps your program running not the absence of a return value.

    Operating Systems *expect* an integer return value, which generally represents an errorlevel... we return 0 to say "no errors"... void main() is a hang over from a wildly outdated, non-standard (even then) compiler that seems not to want to die. You should always use the correct form of ...
    Code:
    int main (void)
      {
         // your code
    
         return 0;  // or an error code
    }
    If you want your program to keep running, make sure the final return statement is outside your loop.
    I realize that return 0; is not a shutdown code, and if I made it seem like that, I apologize. I'm not as experienced with coding as I'm sure most of you are but I do understand that return 0; resulting in a shutdown is related to the operating system expecting a returned value rather than it being a shutdown code. However, as I mentioned in an earlier post, I am dealing with embedded programming that does not have an operating system so returning a value would be pointless. In addition to that, we were specifically told to use void main(void) and not to return a value. If I had a choice, I'd be using int main(void) as I have in the past but I don't have a choice so I'm just following directions.

    Anyways, apparently, qsort is not available, just as laserlight mentioned. Is there any way to achieve the same result (sorting letters in a string alphabetically) without the use of qsort or other similar functions included in stdlib?

  10. #10
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    You're doing the assignment from Message #1 in a microcontroller?
    Is your teacher insane?

    Right now you should be learning about I/O bits, DAC, ADC, interrupts and flash rom sequences...

    What you have there is a C learning exercise... just do it on your PC, using the appropriate program structure.

    Oh wait... that's right... this became an embedded project when we started pointing out your errors... didn't it?
    Last edited by CommonTater; 10-28-2011 at 04:10 AM.

  11. #11
    Registered User
    Join Date
    Aug 2010
    Posts
    231
    Quote Originally Posted by YPavluk View Post
    Anyways, apparently, qsort is not available, just as laserlight mentioned. Is there any way to achieve the same result (sorting letters in a string alphabetically) without the use of qsort or other similar functions included in stdlib?
    You can try this:
    Code:
    void selectionSort( void *p, size_t n, size_t s )
    { /* sort ascending with bigendian byte scope */
      char *a=p,*t=malloc(s);
      int i,j;
    
      for( i=0;i<n-1;++i )
        for( j=i+1;j<n;++j )
          if( memcmp(&a[i*s],&a[j*s])>0 )
          {
            memcpy(t,&a[i*s],s);
            memcpy(&a[i*s],&a[j*s],s);
            memcpy(&a[j*s],t,s);
          }
    
      free(t);
    }
    Its a slow algorithm, it can be called like qsort:
    1.pointer to first element of a sequence of elements
    2.num elements
    3.sizeof any element

    for a string eg:
    Code:
    char s[]="foo bar";
    selectionSort( s, strlen(s), 1);
    Last edited by BillyTKid; 10-28-2011 at 08:49 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sorting strings into alphabetical order
    By dude_tron_1982 in forum C Programming
    Replies: 5
    Last Post: 12-10-2010, 12:34 PM
  2. C++ Alphabetical sorting, etc Help
    By Lucifix in forum C Programming
    Replies: 5
    Last Post: 05-17-2010, 01:29 AM
  3. Alphabetical sorting function
    By typer in forum C Programming
    Replies: 6
    Last Post: 05-20-2006, 02:35 AM
  4. Sorting in alphabetical order
    By fkheng in forum C Programming
    Replies: 3
    Last Post: 08-24-2003, 09:07 AM
  5. Sorting in Alphabetical order
    By Andre Santiago in forum C Programming
    Replies: 1
    Last Post: 12-13-2002, 06:14 PM