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

时间:2019-04-02 23:52:20

标签: 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

我知道一个事实,即在struct中正确给出了值

struct Date{ int year, month, day, hour, minute; }

function(...){ //properly assigns values to Date array }

int comp(const void *t1, const void *t2){
    int t1year = ((const struct Date*)t1)->year;
    int t2year = ((const struct Date*)t2)->year;
    int t1month = ((const struct Date*)t1)->month;
    int t2month = ((const struct Date*)t2)->month;
    int t1day = ((const struct Date*)t1)->day;
    int t2day = ((const struct Date*)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;

    if (t1year < t2year) 
        return -1; 
    if (t1year == t2year && t1month < t2month) 
        return -1; 
    if (t1year == t2year && t1month == t2month && 
    t1day < t2day) 
        return -1;
    if (t1year == t2year && t1month == t2month && 
    t1day == t2day && t1hour < t2hour)
        return -1;
    if (t1year == t2year && t1month == t2month && 
    t1day == t2day && t1hour == t2hour && t1minute < t2minute)
        return -1;
    if (t1year == t2year && t1month == t2month && 
    t1day == t2day && t1hour == t2hour && t1minute == t2minute)
        return 0;
    return 1;
}
void sortArray(struct Date dates[], int n){
        qsort(dates, n, sizeof(Date), comp);
}
...

//prints through a for loop until n

对结果进行排序,但两个时间相同。

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

1 个答案:

答案 0 :(得分:1)

如果第一个值小于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;
    }
}