• 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("
    ");
    24 }
    25 
    26 void ShowStr(int **a)
    27 {
    28     for (int i = 0; i < NUM; i++) {
    29         printf("%s
    ", a[i]);
    30     }
    31     printf("
    ");
    32 }
    33 
    34 void ShowStruct()
    35 {
    36     for (int i = 0; i < NUM; i++) {
    37         printf("%d %d
    ", 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 }
  • 相关阅读:
    alt、title和label
    css3-transform
    word break和word wrap
    聊聊svg
    JS严格模式
    JS提前声明和定义方式
    js跨域
    IE7append新的元素自动补充完整路径
    HTML5摇一摇
    基于jQuery仿uploadify的HTML5图片上传控件jquery.html5uploader
  • 原文地址:https://www.cnblogs.com/hemeiwolong/p/13934642.html
Copyright © 2020-2023  润新知