C qsort没有对所有内容进行完全排序

C qsort没有对所有内容进行完全排序,c,sorting,struct,C,Sorting,Struct,我想对所有元素进行排序,但qsort并没有对所有元素进行完全排序 如果我有约会的话 01/01/2019 15:30 01/01/2019 11:15 01/01/2019 17:00 01/01/2019 15:45 01/01/2019 15:30 01/01/2019 08:00 我知道,在结构中正确地给出了值 结构日期{int year,month,day,hour,minute;} 函数…{//将值正确分配给日期数组} 整数常数无效*t1,常数无效*t2{ int t1year=co

我想对所有元素进行排序,但qsort并没有对所有元素进行完全排序

如果我有约会的话

01/01/2019 15:30
01/01/2019 11:15
01/01/2019 17:00
01/01/2019 15:45
01/01/2019 15:30
01/01/2019 08:00
我知道,在结构中正确地给出了值

结构日期{int year,month,day,hour,minute;} 函数…{//将值正确分配给日期数组} 整数常数无效*t1,常数无效*t2{ int t1year=const struct Date*t1->year; int t2year=施工结构日期*t2->year; int t1month=const struct Date*t1->month; int t2month=施工结构日期*t2->month; int t1day=const struct Date*t1->day; int t2day=施工结构日期*t2->day; int t1hour=const struct Date*t1->hour; int t2hour=const struct Date*t2->hour; int t1minute=const struct Date*t1->minute; int t2minute=const struct Date*t2->minute; 如果t1年
01/01/2019 08:00
01/01/2019 15:30
01/01/2019 11:15    
01/01/2019 15:30
01/01/2019 15:45
01/01/2019 17:00

如果第一个值较小,qsort的比较函数应返回-1;如果第二个值较小,则返回1;如果两者相等,则返回0。在任何情况下都没有返回0,因此没有为该情况返回正确的值

与其建立越来越大的条件来抓住不到的案例,不如反复检查最重要的领域,并深入到最不重要的领域。另外,与其创建大量临时变量,不如创建两个正确类型的指针,然后使用它们

int comp(const void *v1, const void *v2)
{
    const struct Date *t1 = v1;
    const struct Date *t2 = v2;

    if (t1->year < t2->year) {
        return -1; 
    } else if (t1->year > t2->year) {
        return 1; 
    } else if (t1->month < t2->month) {
        return -1; 
    } else if (t1->month > t2->month) {
        return 1; 
    } else if (t1->day < t2->day) {
        return -1; 
    } else if (t1->day > t2->day) {
        return 1; 
    } else if (t1->hour < t2->hour) {
        return -1; 
    } else if (t1->hour > t2->hour) {
        return 1; 
    } else if (t1->minute < t2->minute) {
        return -1; 
    } else if (t1->minute > t2->minute) {
        return 1; 
    } else {
        return 0;
    }
}

comp函数在两个相等的时间内返回错误的值。与其在比较函数中指定10个局部变量,不如使用int compconst void*vp1,const void*vp2{const struct Date*t1=vp1;const struct Date*t2=vp2;然后使用if t1->yearyear return-1,如果t1->year>t2->year return+1,则使用else if t1->monthmonth return-1;否则返回0;这也修复了在等式上返回错误值的剩余问题。