Sorting an array using multiple sort criteria (QuickSort)

前端 未结 5 1640
傲寒
傲寒 2020-12-21 05:09

I am trying to find out how (using a quicksort algorithm) to sort an struct array by 2 criterias. For example say I had a struct of:

struct employee{
   char         


        
5条回答
  •  爱一瞬间的悲伤
    2020-12-21 05:49

    int compare_employee (struct employee * a, struct employee * b) {
        int diff = strcmp(a->gender, b->gender);
    
        if (diff) // if gender different
            return -diff; // sort descending, please double check this and reverse in case I am wrong
    
        return a->id - b->id; // else sort by id
    }
    

    Will output a negative number if a < b, positive if a > b, zero if they are equal.

    Use it eigther in your own quicksort or as a qsort comparator.

提交回复
热议问题