• 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);
    }
    
  • 相关阅读:
    其它运算符
    位运算符
    赋值运算符
    逻辑运算符
    关系运算符
    理解twisted中的reactor和deferred(一)
    修改 Django Administration
    celery 调用scrapy
    flower 时区设置
    Python 过滤HTML实体符号简易方法
  • 原文地址:https://www.cnblogs.com/wangshaodong/p/13510900.html
Copyright © 2020-2023  润新知