• C 语言标准库中的qsort函数使用


    • 排序函数 qsort

      // 头文件 <stdlib.h>

    void qsort(void *base/*数组的起始地址*/, size_t nmemb/*数组元素个数*/, size_t size/* 数组每个元素的大小*/,
      int (*compar)(const void *, const void *));
    
    The qsort() function sorts an array with nmemb elements of size size. 
    The base argument points to the start
    of the array.
    
    The contents of the array are sorted in ascending order according to a comparison function pointed to by compar, which is called with two arguments that point to the objects being compared.
    /*排序结果默认升序,可以通过修改compare 函数来达到降序的结果 */
    The comparison function must return an integer less than, equal to, or greater than zero if the first argument
    is considered to be respectively less than, equal to, or greater than the second. If two members compare as
    equal, their order in the sorted array is undefined.
    /* 
    假设自定的compare 函数的为int (*compar)(const void *a, const void *b)
    则返回值应该是,如果a < b 则小于0, 如果元素a > b 则小于0,如果相等则 返回 0;
    如果a == b,这两个元素的再排序完成的数组中位置不确定, 属于不稳定的排序算法
    */
    

    百度百科也有资料介绍, 比较通俗易懂

    // 代码来自wikipedia
    #include <stdlib.h>
    
    /* Comparison function. Receives two generic (void) pointers to the items under comparison. */
    int compare_ints(const void *p, const void *q) {
        int x = *(const int *)p;
        int y = *(const int *)q;
    
        /* Avoid return x - y, which can cause undefined behaviour
           because of signed integer overflow. */
        if (x < y)
            return -1;  // Return -1 if you want ascending, 1 if you want descending order. 
        else if (x > y)
            return 1;   // Return 1 if you want ascending, -1 if you want descending order. 
    
        return 0;
    }
    
    /* Sort an array of n integers, pointed to by a. */
    void sort_ints(int *a, size_t n) {
        qsort(a, n, sizeof(*a), compare_ints);
    }
    
  • 相关阅读:
    Shell重新学习(忘光了)
    vim 设置默认显示行号
    maven学习资料(三)
    maven:新建的maven工程需要添加一下插件
    Spring框架:第五章:Spring EL表达式
    Spring框架:第四章:Spring管理数据库连接池
    Spring框架:第三章:对象的生命周期及单例bean生命周期的11个步骤
    Spring框架:第二章:IOC依赖注入及40个实验
    Spring框架:第一章:介绍和准备工作
    MyBatis框架:第十一章:mybatis 逆向工程
  • 原文地址:https://www.cnblogs.com/wangshaodong/p/13510900.html
Copyright © 2020-2023  润新知