当前位置:   article > 正文

C语言-使用qsort函数对自定义结构体数组进行排序_写一个c语言函数,对数组元素排序

写一个c语言函数,对数组元素排序

qsort进行排序的数组存储的不能是结构体的指针,需要是结构体本身。

结构体

struct student{
    char* id;
    int mark;
}arr[4],
test0={"0001",80},
test1={"0002",90},
test2={"0003",60},
test3={"0004",61}
;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

排序函数

int cmp(const void *a, const void *b){
    int mark1=((struct student *)a)->mark;
    int mark2=((struct student *)b)->mark;
    return mark1>mark2 ? 1:-1;
}
  • 1
  • 2
  • 3
  • 4
  • 5

总体代码

#include <stdio.h>
struct student{
    char* id;
    int mark;
}arr[4],
test0={"0001",80},
test1={"0002",90},
test2={"0003",60},
test3={"0004",61}
;
int cmp(const void *a, const void *b){
    int mark1=((struct student *)a)->mark;
    int mark2=((struct student *)b)->mark;
    return mark1>mark2 ? 1:-1;
}
int main(){
    arr[0]=test0;arr[1]=test1;arr[2]=test2;arr[3]=test3;
    printf("—————排序前—————\n");
    for(int i=0; i<4; i++)
        printf("%s %d\n",arr[i].id,arr[i].mark);
    qsort(arr,4,sizeof(struct student),cmp);
    printf("—————排序后—————\n");
    for(int i=0; i<4; i++)
        printf("%s %d\n",arr[i].id,arr[i].mark);
    return 0;
}
  • 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

结果

—————排序前—————
0001 80
0002 90
0003 60
0004 61
—————排序后—————
0003 60
0004 61
0001 80
0002 90
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/136640
推荐阅读
相关标签
  

闽ICP备14008679号