Thread: Sorting Elements in Lexicographical Order

  1. #1
    Registered User
    Join Date
    Jan 2013
    Posts
    108

    Sorting Elements in Lexicographical Order

    Hey guys,
    I have a code here i'm using for an exercise and basically it sorts a group of words of the user's choice and prints them in Dictionary order.

    I have a few questions as I'm new to C programming and it's my first year of Computer Science.

    First of all here's the code:
    ( sorry the code is like this.. don't know how to post it better )
    Code:
    1 #include<stdio.h>
    2 #include <string.h>
    3 int main(){
    4    int i,j;
    5    char str[10][50],temp[50];
    6    printf("Enter 10 words:\n");
    7    for(i=0;i<10;++i)
    8        gets(str[i]);
    9    for(i=0;i<9;++i)
    10        for(j=i+1;j<10 ;++j){
    11            if(strcmp(str[i],str[j])>0)
    12            {
    13                strcpy(temp,str[i]);
    14                strcpy(str[i],str[j]);
    15                strcpy(str[j],temp);
    16            }
    17        }
    18    printf("In lexicographical order: \n");
    19    for(i=0;i<10;++i){
    10        puts(str[i]);
    21    }
    22    return 0;
    23 }

    1st Question: Line-7 the for loop explains that user's printing 10 words no more (True/False)
    2nd Question: Line-9 & 10 don't understand this loop. Can someone explain me?
    3rd Question: Now i understand that the user needs to print 10 words after hitting "Enter" but how to change this code so that the user can insert a serie of words using spaces instead of pressing "Enter"?
    I want it to scan only the first line that contains my group of words.
    example: john jordan jake yann max kevin
    instead of:
    john
    jordan
    jake
    yann
    max
    kevin
    Last edited by YannB; 01-14-2013 at 01:46 PM.

  2. #2
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    There is a preview option. You may start using it

    Edit your code, so that it does not lie in a single line (!)

    Change the color of the questions.
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  3. #3
    Registered User
    Join Date
    Jan 2013
    Posts
    108
    here!
    any help?

  4. #4
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Nice!

    Don't use gets.

    A1 - Wrong. It just prints the message into the screen. The user can do whatever he wants. But, for now (because you are a starter), I suggest you trust him (for now only).

    A2 - It sorts the words. It is the bubblesort. In the link you can see how it works.

    A3 - Why? It can be done, but you are a starter.

    About the relation between users and programmers :
    Sorting Elements in Lexicographical Order-userprogrammers-jpg
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    What do you mean by "scan only the first line"?

    You have code that enters names, into the array:
    john
    jordan
    jake
    yann
    max
    kevin

    as one word per line (there is a newline between each word, created when you hit enter when you used gets() - scanf() would also put each name, into it's own line).

    So I don't understand what you want - do you want the words printed out in one line, in sorted order, maybe?

    Your sort code is VERY close to a bubble sort - but technically, it's a Substitution sort. In a Bubble sort, only adjacent elements are compared. In a Substitution sort, adjacent elements are only compared on the first iteration of the inner for loop. After that the elements being compared get further and further apart.
    Last edited by Adak; 01-14-2013 at 02:09 PM.

  6. #6
    Registered User
    Join Date
    Jan 2013
    Posts
    108
    Thanks for the reply.
    First of all concerning Q1: didn't understand your answer for the for loop code:
    Code:
     for (i=0;i<10;++i)
    Concerning Q3: Could you tell me exactly how to change the code for it to scan only one line of a group of word instead of entering word one by one followed by "Enter"?

  7. #7
    Registered User
    Join Date
    Jan 2013
    Posts
    108
    I need to the group of words in one line instead of pressing enter every time i type a word.
    Sorry if i'm not clear enough

  8. #8
    Registered User
    Join Date
    Sep 2011
    Posts
    25
    Hey, YannB. Here is some sample code to take a string and separate it into words, or "tokens."

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main()
    { 
       int i,garbage;
       char *tokenPtr;
       char string[1000];//If you know how to use define statements, it is a great idea to use them instead of the magic number 1000 here
       
       printf("Please type exactly ten words separated by spaces onto the screen, followed by the enter key.\n");
       gets(string);//You shouldn't use gets but since it's what you're already using it, I'll follow your current convention
              
       tokenPtr = strtok( string, " " );
       
    
       for ( i=0;i<10;i++ ) { 
          printf("%s\n",tokenPtr);
          tokenPtr = strtok( NULL, " " );
       }
    
       scanf("%d",&garbage);
       return 0;
    
    }
    This code may not be perfect (I am a new user here and still getting my footing on accepted practices) but it compiles and accomplishes its task.
    There is a problem, however. Your alphabetical sorting code (the nested for loops starting at line 9 of your current code) will need to be changed for this new type of string evaluation.

  9. #9
    Registered User
    Join Date
    Jan 2013
    Posts
    108
    sick thanks!
    quick question: why shouldn't i use gets?
    and with what to replace it? just scanf?

  10. #10
    Registered User
    Join Date
    Sep 2011
    Posts
    25
    No problem

    A great alternative to gets is fgets. std10093 has provided a great link on the problems inherent in gets, and here is a link on how to use fgets from this site as well:
    FAQ > Get a line of text from the user/keyboard (C) - Cprogramming.com

    Hope that helps!
    Also: std10093, how did you make that set of words a clickable link (Don't use gets)?
    Last edited by Derek Lake; 01-14-2013 at 02:31 PM. Reason: clarification of my question

  11. #11
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    why shouldn't i use gets?
    FAQ > Why gets() is bad / Buffer Overflows - Cprogramming.com

    and with what to replace it? just scanf?
    Use "fgets()" instead. "scanf()" will stop reading at the first space (unless you use complicated trickery).

  12. #12
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    OK. Now I got ya. A bit different than Derek's algorithm, above.


    You'll want to test this thoroughly, as I have not. Looks OK though, for 5 words, only.

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void) {
    
       int i,j,n;
       char words[5][30], buffer[302];
    
       printf("Enter your names, with one space between them: \n");
       fgets(buffer, sizeof(buffer), stdin);
    
       printf("%s",buffer);
       n=strlen(buffer);
       if(buffer[n-1]=='\n');
          buffer[n-1]='\0';
    
       for(i=0,j=0;i<5;i++) {
          sscanf(buffer+j, "%s",words[i]);
          j+=strlen(words[i])+1;
    
    
       }
       for(i=0;i<5;i++) {
          printf("%s \n",words[i]);
       }
       return 0;
    }
    Last edited by Adak; 01-14-2013 at 02:43 PM.

  13. #13
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Quote Originally Posted by YannB View Post
    quick question: why shouldn't i use gets?
    Answered in post #4.
    Quote Originally Posted by Matticus View Post
    FAQ > Why gets() is bad...
    Forcing Matticus to rewrite the same thing.. Almost a duplicate. This make post's length unnecessary get increased by one.
    Show, it would be nice if everybody (including me) read the whole posts, because the words have something to say!
    Quote Originally Posted by Derek Lake View Post
    Also: std10093, how did you make that set of words a clickable link (Don't use gets)?
    Derek you :
    • write the string you want
    • you select with the mouse (just like when you want to copy paste it)
    • On the toolbar above the textbox we write our posts, there is a toolbar
      On the rightmost container, the leftmost element of it is something like a globe with the link sign.
    • Click on it.
    • Pop-up box appears requesting you to provide the url of the link (the link of the faq in my case, which I copy pasted it)
    • Click ok and that must be all...
    • If not, don't hesitate to ask me back


    //thanks whiteflag for the spelling tip
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 05-26-2011, 10:01 AM
  2. sorting ABC order
    By rodrigorules in forum C++ Programming
    Replies: 4
    Last Post: 02-22-2010, 01:37 AM
  3. Replies: 8
    Last Post: 10-21-2007, 01:38 PM
  4. printing array elements in ascending order
    By galmca in forum C Programming
    Replies: 29
    Last Post: 10-24-2004, 11:24 PM
  5. Sorting in Alphabetical order
    By Andre Santiago in forum C Programming
    Replies: 1
    Last Post: 12-13-2002, 06:14 PM