qsort function - trying to use a comparator

后端 未结 3 2037
执念已碎
执念已碎 2021-01-23 10:54

I made a qsort function for a larger program. It is to sort by time. I have a class schedule I am working with and found a need to compare time with AM and PM. ie if A is chosen

3条回答
  •  忘掉有多难
    2021-01-23 11:25

    Just add separate check for AM vs PM and make any AM time be less than PM time:

    int sortFunction(const void *p, const void *q) {
      return
        (sched_record *) p)->am_pm < (sched_record *) q)->am_pm ?
          -1 :
        (sched_record *) p)->am_pm > (sched_record *) q)->am_pm ?
           1 :
           ((sched_record *) p)->start.hour -
                   ((sched_record *) q)->start.hour;
    }
    

    presumably in your sched_record the am_pm field will hold 1 for am and 2 for pm, or something like that.

    edit: turns out the OP doesn't have am_pm indicator in their structure and so must probably use 24 hour time representation, apparently with integers for hours and minutes:

    int sortFunction(const void *p, const void *q) {
      return
        (sched_record *) p)->start.hour < (sched_record *) q)->start.hour ?
          -1 :
        (sched_record *) p)->start.hour > (sched_record *) q)->start.hour ?
           1 :
           ((sched_record *) p)->start.minutes -
                   ((sched_record *) q)->start.minutes;
    }
    

提交回复
热议问题