C语言stdlib.h下的qsort<快速排序>

函数原型

void qsort(void *__base, size_t __nel, size_t __width, 
            int (* _Nonnull __compar)(const void *, const void *));

实例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// int 变量排序
int compareInt(const void *a, const void *b) {
    return *(int *) a - *(int *) b;
}

int compareString(const void *a, const void *b) {
    return strcmp((char *) a, (char *) b);
}

int main() {
    const int len = 10;
    int a[len];

    // 数组排序
    for (int i = 0; i < len; ++i) {
        a[i] = rand() % 100; // [0, 99]
    }
    printf("排序前\n");
    for (int j = 0; j < len; ++j) {
        printf("%d\t", a[j]);
    }
    printf("\n");
    /*
     * 参数1:待排序数组首地址
     * 参数2:带排序的元素总个数 < const int len = 10 或者 #define LEN 10 >
     * 参数3:单个元素占用空间大小
     * 参数4:比较规则,a-b 从小到大,b-a 从大到小
     */
    qsort(a + 4, len - 4, sizeof(int), compareInt); // 前4个数不参与排序
    printf("排序后\n");
    for (int j = 0; j < len; ++j) {
        printf("%d\t", a[j]);
    }
    printf("\n");

    // 字符串排序
    char names[5][10] = {"WebStorm", "Pycharm", "IntelliJ", "CLion", "PhpStorm"};
    printf("排序前\n");
    for (int k = 0; k < 5; ++k) {
        printf("%10s\t", names[k]);
    }
    printf("\n");
    qsort(names, 5, 10 * sizeof(char), compareString);
    printf("排序后\n");
    for (int k = 0; k < 5; ++k) {
        printf("%10s\t", names[k]);
    }
    return 0;
}
排序前
7   49  73  58  30  72  44  78  23  9   
排序后
7   49  73  58  9   23  30  44  72  78  
排序前
  WebStorm     Pycharm    IntelliJ       CLion    PhpStorm  
排序后
     CLion    IntelliJ    PhpStorm     Pycharm    WebStorm  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值