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

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

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   More study needed.  阅读(519)  评论(0编辑  收藏  举报

编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
< 2012年9月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 1 2 3 4 5 6

导航

统计

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

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

点击右上角即可分享
微信分享提示