Hello i have an array of struct objects represent time schedules.i need to sort them in an order such that the first most element after sort is closest past to current day.
The struct looks like this:
struct ScheduleItem {
int index;
int hh;
int mm;
int dow;
long reg_timestamp;
};
index
=> arbitrary index number
hh
=> hour (24)
mm
=> minute
dow
=> day of week (starting sunday = 0)
reg_timestamp
=> epoch time when the schedule was created
Following are the sample schedules stored in an array of schedules called user_schedules
.
index:HH:MM:DOW:EPOCH
1:20:30:0:1550951769
2:03:15:0:1550951769
2:20:30:1:1550951769
3:03:15:1:1550951769
3:20:30:2:1550951769
4:03:15:2:1550951769
4:20:30:3:1550951769
5:03:15:3:1550951769
6:03:15:4:1550951769
Assume today is 2:00 am
Saturday
(dow = 6)
How to use qsort to sort it such that
the array is sorted in an order with first most element being closest past
to current date. I just know of sorting ascending or descending so not able to get what want.
This is what i tried:
qsort((void *) &applicable_schedules, counter, sizeof(struct ScheduleItem), (compfn)nearestPast );
candidate = applicable_schedules[0];
/**
* Compare to sort nearest past schedule
*/
int nearestPast(struct ScheduleItem *elem1, struct ScheduleItem *elem2)
{
if ( elem1->reg_timestamp == elem2->reg_timestamp)
{
return abs(elem1->dow - elem2->dow);
}
else
{
return elem1->reg_timestamp - elem2->reg_timestamp;
}
}
and i got 20:30:0:1550951769
, which is Sunday
(incorrect of-course)
I am not a c guy so have issue understanding sorting in this case.
This code is for arduino
UPDATE
For more clarification closest past should be by day of week as well as HH:MM