Parallel arrays, dynamic memory allocation, and sorting arrays

This is a discussion on Parallel arrays, dynamic memory allocation, and sorting arrays within the C Programming forums, part of the General Programming Boards category; >> for instance, sort first by name, then by score; or by last name then first name. Why would it ...

  1. #16
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,526
    >> for instance, sort first by name, then by score; or by last name then first name.

    Why would it make sense to sort by name twice?

    Have you considered using qsort in any way? It may be simpler just to focus on how elements compare to one another rather than writing a new, untested sort, especially since the sorting is so complex.

    Code:
    struct sorter {
       struct record * data;
       unsigned int index;
    };
    
    void 
    filtered_sort ( struct record * list, unsigned int * parallel, unsigned int nelem ) {
       struct sorter * temp = make_it ( list, nelem );
       if ( temp ) {
          unsigned int i;
          for ( i = 0; i < nelem-1; i++ ) { 
             temp[i].data = &list[i];
             temp[i].index = i;
          }
          qsort( temp, sizeof temp / sizeof temp[0], sizeof temp[0], filter_sort );
          for ( i = 0; i < nelem-1; i++ ) { parallel[i] = temp[i].index; }
          free( temp );
          temp = 0;
       }
    }
    Assuming make_it returns an array of sorter objects the correct size, I think this is some okay pseudo-code... just figure out how to write a comparison function that
    • attempts to sort by last name
    • then first name
    • then by score

    trying to minimize as many "ties" as possible.

    The parallel array filtered_sort fills can be used to access an array of unsorted records.
    Last edited by whiteflags; 01-01-2008 at 02:59 PM.

  2. #17
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Quote Originally Posted by sbaker1313 View Post
    Thanks guys. Per your advice, I changed my function definition to...

    Code:
    void namesort(int n, int usenum, char list[][MAXNAME], int sort[])
    but at compile time it says, "conflicting types for 'namesort'". Any thoughts? And how would I call this function?
    I'm guessing that means you forgot to change the prototype at the top of your source file.

    To call it, you just need to pass in everything that's asked for: two integers (maybe? I don't see where n is used), a 2-D char array (such as lastname), and the array of indices. The integers n and usenum can't be changed by the function, but sort[] can.

Page 2 of 2 FirstFirst 12
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 26
    Last Post: 06-11-2009, 11:27 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21