书山有径勤为路>>>>>>>>

<<<<<<<<学海无涯苦作舟!

qort的用法总结

两点注意:

1. cmp函数必须返回int型。

2.qsort中必须有4个参数。也就是说一定有cmp函数存在,不然它不知道怎么排序。

 

Number 1: int 型排序。(数组)

View Code
……
int intcmp(const void *a, const void *b)
{
    return (*(int*)a)-(*(int*)b);
}
int main()
{
        int n[10]={1, 3, 4, 9, 7, 0 , 8, 5, 4, 3};
        qsort(n, 10, sizeof(n[0]), intcmp);
        ……
}

 

Number 2: double型排序(数组)要特别注意一下。

View Code
……
int cmp1(const void* a, const void* b)
{
    double aa=(*(double*)a), bb=(*(double*)b);//注意是double不是int否则丢失精度,也不能写成return aa-bb;
    return aa<bb?-1:1;
}
int main()
{
    int y[5]={1,3,4,8,4};
    qsort(y, 5, sizeof(y[0]), cmp1);
    ……
}

 

Number 3:char型排序。(字符串)

View Code
……
int charcmp(const void *a, const void *b)
{
    return strcmp((char*)a, (char*)b);//strcmp的参数要求的就是指针,所以不用再加*了
}
int main()
{
    char s[4][20]={"addsf", "abvcd", "aldfj", "dsfd"};
    qsort(s, 4, sizeof(s[0]), charcmp);
}

 

Number 4:node型排序。(结构体)

View Code
……
int structcmp(const void *a, const void *b)
{
    node aa=*(node*)a, bb=*(node*)b;
    if(aa.x < bb.x) return -1;
    else if(aa.x > bb.x) return 1;
    else if(aa.y < bb.y) return -1;
    else if(aa.y > bb.y) return 1;
    else return 0;
}
int main()
{
    node t[5];
    t[0].x=1, t[0].y=4;
    t[1].x=9, t[1].y=3;
    t[2].x=3, t[2].y=4;
    t[3].x=3, t[3].y=5;
    t[4].x=1, t[4].y=4;
    qsort(t, 5, sizeof(t[0]), structcmp);
}

posted on 2012-09-01 20:31  More study needed.  阅读(513)  评论(0编辑  收藏  举报

导航

书山有径勤为路>>>>>>>>

<<<<<<<<学海无涯苦作舟!