• (c语言)qsort()函数排序结构体


    1. #include
    2. #include
    3. #include
    4. //void qsort          qsort()函数初始是递增排序
    5. // (void* base,       要排序的初始位置
    6. // size_t num,        待排序的元素个数
    7. // size_t width,      待排序的数据元素的大小(字节)
    8. // int(*cmp)(const void* e1,const void* e2))    函数指针—比较函数
    9. //_cdecl——函数调用约定,约定函数由c语言的语法调用
    10. //函数定义要求e1-e2>0时输出整数,e1-e2=0时输出1=0,e1-e2<0时输出负数
    11. //qsort()函数初始是递增排序,若要变为递减排序,则要交换e1和e2
    12. struct Stu
    13. {
    14.     char name[20];
    15.     int age;
    16. };
    17. //设置比较函数
    18. int cmp1(const void* x1, const void* x2)
    19. {
    20.     return strcmp(((struct Stu*)x1)->name,((struct Stu*)x2)->name);
    21. }
    22. int cmp2(const void* x1, const void* x2)
    23. {
    24.     return ((struct Stu*)x1)->age - ((struct Stu*)x2)->age;
    25. }
    26. void test1()        //排序结构体的name元素
    27. {
    28.     struct Stu s[3] = { {"zhangsan",15},{"lisi",30},{"wangwu",25} };
    29.     int sz = sizeof(s) / sizeof(s[0]);
    30.     qsort(s, sz, sizeof(s[0]),cmp1);
    31.     for (int i = 0; i < 3; i++)
    32.     {
    33.         printf("%s ", s[i].name);
    34.     }
    35. }
    36. void test2()    //排序结构体的age元素
    37. {
    38.     struct Stu s[3] = { {"zhangsan",15},{"lisi",30},{"wangwu",25} };
    39.     int sz = sizeof(s) / sizeof(s[0]);
    40.     qsort(s, sz, sizeof(s[0]), cmp2);
    41.     for (int i = 0; i < 3; i++)
    42.     {
    43.         printf("%d ", s[i].age);
    44.     }
    45. }
    46. int main()
    47. {
    48.     test1();
    49.     printf("\n");
    50.     test2();
    51.     return 0;
    52. }

  • 相关阅读:
    总结git常用命令
    修复所有 bug 并不能解决所有问题
    【Linux】《Linux命令行与shell脚本编程大全 (第4版) 》笔记-Chapter1-初始 Linux Shell
    【定语从句练习题】定语从句的理解层次
    学习c#的第一天
    数据增强功能工具,选项功能对照表
    Linux进程概念
    通信真的是天坑专业吗?应届毕业生出来能做什么?
    lNmp安装:
    RBTree的删除
  • 原文地址:https://blog.csdn.net/2301_79580018/article/details/133698695