zoukankan      html  css  js  c++  java
  • 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);
    }
    
  • 相关阅读:
    编译原理 十
    使用HighCharts实现实时数据展示
    img图片元素下多余空白解决方案
    jquery 滚动加载
    SVN服务器配置
    匿名对象和object的转换
    新浪微博开放平台OAuth授权解决方案(含代码)
    QQ互联OAuth2.0 .NET SDK 发布以及网站QQ登陆示例代码
    Senparc.Weixin.MP SDK 微信公众平台开发教程(七):解决用户上下文(Session)问题
    Senparc.Weixin.MP SDK 微信公众平台开发教程(六):了解MessageHandler
  • 原文地址:https://www.cnblogs.com/wangshaodong/p/13510900.html
Copyright © 2011-2022 走看看