美文网首页
C语言 day12

C语言 day12

作者: y_7539 | 来源:发表于2022-09-21 14:13 被阅读0次

    qsort排序

    #define _CRT_SECURE_NO_WARNINGS 1
    #include <stdio.h>
    #include <string.h>
    
    int com_num(const void* n1, const void* n2) {
    
        return *(int*)n1 - *(int*)n2;
    }
    
    
    void test1() {
    
        int arr[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
        int sz = sizeof(arr) / sizeof(arr[0]);
        qsort(arr, sz, sizeof(arr[0]), com_num);
        for (int i = 0;i < sz;i++) {
    
            printf("%d ", arr[i]);
        }
    }
    
    struct Student
    {
        char name[10];
        int age;
    };
    
    int com_age(const void* s1, const void * s2)
    {
        return ((struct Student*)s1)->age - ((struct Student*)s2)->age;
    }
    
    int com_name(const void* s1, const void* s2)
    {
        return strcmp(((struct Student*)s1)->name, ((struct Student*)s2)->name);
    }
    
    void test2()
    {
        struct Student stu[3] = { {"zhangsan", 29},{"lisi", 22},{"wangwu", 21} };
        int sz = sizeof(stu) / sizeof(stu[0]);
        //qsort(stu, sz, sizeof(stu[0]), com_age);
        qsort(stu, sz, sizeof(stu[0]), com_name);
        for (int i = 0; i < sz; i++)
        {
            printf("%s %d\n",stu[i].name, stu[i].age);
        }
    }
    
    
    
    //快排  qsort
    int main() {
        // test1();
        test2();
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:C语言 day12

          本文链接:https://www.haomeiwen.com/subject/eamwortx.html