c语言qsort使用

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <stdbool.h>
 4 #include <string.h>
 5 
 6 #define NUM 3
 7 
 8 typedef struct {
 9     int a;
10     int b;
11 } Node;
12 Node nodes[] = {
13     { 2, 3 },
14     { 8, 3 },
15     { 2, 9 }
16 };
17 
18 void ShowNum(int *a)
19 {
20     for (int i = 0; i < NUM; i++) {
21         printf("%d ", a[i]);
22     }
23     printf("\n");
24 }
25 
26 void ShowStr(int **a)
27 {
28     for (int i = 0; i < NUM; i++) {
29         printf("%s\n", a[i]);
30     }
31     printf("\n");
32 }
33 
34 void ShowStruct()
35 {
36     for (int i = 0; i < NUM; i++) {
37         printf("%d %d\n", nodes[i].a, nodes[i].b);
38     }
39 }
40 
41 int CmpNum(const void *a, const void *b)
42 {
43     return (*(int *)a - *(int *)b);
44 }
45 
46 int CmpStr(const void *a, const void *b)
47 {
48     return strcmp(*(char **)a, *(char **)b);
49 }
50 
51 int CmpStruct(const void *a, const void *b)
52 {
53     Node *pa = (Node *)a;
54     Node *pb = (Node *)b;
55 
56     if (pa->a == pb->a) {
57         return pa->b - pb->b;
58     }
59     return pa->a - pb->a;
60 }
61 
62 int main()
63 {
64     // 排序数字
65     int values[] = {88, 56, 100};
66     qsort(values, NUM, sizeof(int), CmpNum);
67     ShowNum(values);
68 
69     // 排序字符串
70     char *a[] = {"uhhkjhkj",
71                  "dffgfg",
72                  "kgyjhk"};
73     qsort(a, NUM, sizeof(char *), CmpStr);
74     ShowStr(a);
75 
76     // 排序结构体
77     qsort(nodes, NUM, sizeof(Node), CmpStruct);
78     ShowStruct();
79 
80     return 0;
81 }

 

posted @ 2020-11-05 23:33  hemeiwolong  阅读(101)  评论(0编辑  收藏  举报