Thread: Sorting Array of Strings

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    30

    Sorting Array of Strings

    I am just getting into the various search methods/functions/algorithms available in C. The only function I have come across in the K&R book or online in example C code is the 'qsort' function. I have learned how it works watching some youtube videos, and I know how to sort a list of integers or strings using it. In the example code that I have found online, qsort always uses the ASCII values of each character in a string in a 'comparison function' to return a positive number, negative number, or zero. This is convenient if one wants to sort an array of strings alphabetically, since the value of 'a' < 'b' < 'c' < 'd' < 'e'.... in ASCII.

    I want to know how to sort a list of strings some other way. I do not want to do it alphabetically, and thus I need to know how to setup a comparison function to sort strings differently, using some sort of legend or key that I designate.

    For example, say I had a list of positions in a company, and I wanted to sort a list of company positions. If 'President' were the most powerful position, and I wanted it at the top of my list after sorting, how could I define President as the 'number 1' position, meaning it should be sorted to the front of the list, (not based on the value of 'P' in ASCII, which might throw 'President' to the middle or end of the list).

    I'm very new to programming, so I'm not familiar with all of the tools at my disposal. The only method I have thought of on my own is to create a new array of integers and assign numerical values to certain specific strings. Then, perform qsort on an array of integers, and then take that newly created array and convert it back to the corresponding strings. This converting to integers and converting back to strings seems like it would be inefficient, but I don't know of a better way due to my programming ignorance. Should I use qsort another way? Should I use some other function besides qsort for this task?
    Last edited by nair; 10-06-2010 at 11:03 PM.

  2. #2
    Novice
    Join Date
    Jul 2009
    Posts
    568
    For complex data, such as, in your example, a position in a company, you will have to find a way to assign arbitrary 'weight' to it. Then, sort by this weight. Structures might be involved in this.

  3. #3
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Don't use a comparison sort like qsort. Use a bucket sort first. Imagine each position as a bucket.

  4. #4
    Registered User
    Join Date
    Oct 2010
    Posts
    30
    I just figured out how to declare a 'struct' in C last night, and I think I should probably use one for this task.

    If I create a struct, I can define the first member of that struct as the strings that are found in the array. Then I can create a second member which will be like an ID number. With that struct in place, I can sort the struct elements based on the value of the ID number using something like qsort. I have not actually done that part yet, but it seems doable. I do not know if its efficient or not, but it seems like a reasonably straight-forward approach.

  5. #5
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Sounds like a good solution. You could do it with just an array of strings, of course.
    Code:
    const char *titles[] = {
        "President",
        "Vice-president",
        /* ... */
    };
    Then you could just (linear) search in the titles[] array for the correct title, and the index in the array would be the "rank" of that title which you could use in a qsort() comparison function. For example (to determine rank):
    Code:
    for(size_t x = 0; x < sizeof(titles) / sizeof(*titles); x ++) {
        if(!strcmp(this_title, titles[x])) return x;
    }
    (The sizeof() trick there just returns the number of elements in an array.)

    But it may be more interesting to use structures -- by the way, you may be interested in this C syntax that allows you to initialize an array of structures . . .
    Code:
    struct title_t {
        const char *name;
        int rank;
    } titles[] = {
        {"President", 1},
        {"Vice-president", 2},
        /* ... */
    };
    The nice thing about doing this is that you could potentially have big gaps in the ranks (in case you use them for something else), or you could even do a binary search if you keep the names in sorted order. (Don't try to figure out a binary search out of your own head, by the way: it's nearly impossible . . . find some book or resource online to use as a basis.) Binary search is probably complete overkill in this situation of course, since it's much harder to code for little benefit on small-sized lists, but it's interesting to think about nevertheless . . . .

    [Side note: I've used const char* pointers because string literals, strings that you type into the code between double quotes, are technically constant and are not supposed to be changed.]
    Last edited by dwks; 10-08-2010 at 08:37 PM.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  6. #6
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Actually one thought would be to build a simple struct for each person:

    Code:
    struct Employees
        { char name[40];
           char rank[40];
           int group; }
    then use an enum to assign weights...

    Code:
    enum "President","Vice","CEO"
    make one pass through and assign weights to each employee according to rank.

    Then do a sort of the whole list on rank and use pocket sorts --sorting within each rank-- to alpha order each group.

  7. #7
    Registered User baffleddreams's Avatar
    Join Date
    Aug 2010
    Location
    India
    Posts
    15

    Wink use strcmp() function

    u can use the strcmp() function ...
    char s[n][20];//where n is d no of strings
    insert
    Code:
    for(i=0;1<n;i++)
    {
                for(j=i+1;j<n;j++)
                {
                                  if(strcmp(s[j],s[i])>0)
                                  {
                                                swap s1&s2
                                   }
               }
    }
    its something like bubble sort!!try it it works..

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Swapping strings in an array of strings
    By dannyzimbabwe in forum C Programming
    Replies: 3
    Last Post: 03-03-2009, 12:28 PM
  2. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  3. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  4. Merge sort please
    By vasanth in forum C Programming
    Replies: 2
    Last Post: 11-09-2003, 12:09 PM
  5. Array of Strings
    By mjpars in forum C Programming
    Replies: 8
    Last Post: 08-21-2003, 11:15 PM