Thread: qsort on multiple indexes ex. primary index then secondary index

  1. #1
    Registered User
    Join Date
    Aug 2011
    Posts
    1

    Exclamation qsort on multiple indexes ex. primary index then secondary index

    What would be the best way to implement a qsort that does sort on multiple indexes. ex. first sort on primary index then secondary index.

    Code:
    //before sort: {(0, 3),(1, 2),(0, 1)}
    //after sort: {(0, 1),(0, 3),(1, 2)}

    Code:
    typedef struct{
    boolean element1;//primary
    int element2;//secondary
    }foo
    
    int my_cmp(){
    //?? what would be the most efficient implementation
    }
    int main(){
    foo a[20]; 
    //assume the array gets filled here
    
    qsort(&a[0], sizeof(a),sizeof(a[0]), my_cmp);
    
    return 0;
    }
    Thank you!

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    It basically goes like this
    Code:
    if ( a.e1 < b.e1 ) return -1;
    if ( a.e1 > b.e1 ) return +1;
    // e1 is equal, now go onto e2
    if ( a.e2 < b.e2 ) return -1;
    if ( a.e2 > b.e2 ) return +1;
    // all the keys are equal
    return 0;
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. short index vs. int index
    By ardavirus in forum C Programming
    Replies: 3
    Last Post: 06-13-2011, 05:09 AM
  2. Longest Index
    By megazord in forum C Programming
    Replies: 3
    Last Post: 12-12-2009, 08:32 AM
  3. Permuted Index Help
    By dnguyen1022 in forum C++ Programming
    Replies: 2
    Last Post: 03-27-2009, 11:03 PM
  4. ? about this> index::index () : type_intex()
    By bobk544 in forum C++ Programming
    Replies: 5
    Last Post: 09-30-2005, 02:59 PM
  5. Tab index
    By Micko in forum Windows Programming
    Replies: 3
    Last Post: 07-14-2004, 07:05 PM