Thread: Parallel arrays, dynamic memory allocation, and sorting arrays

  1. #16
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    United States
    >> 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.

    struct sorter {
       struct record * data;
       unsigned int index;
    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 03:59 PM.

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

    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 26
    Last Post: 06-11-2009, 12:27 PM
Website Security Test