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);
    }
    
  • 相关阅读:
    C++ 解析CSV文件
    MFC/WTL 设置背景图和控件透明的方法
    VS2008安装x64版本所遇问题
    VS2012 安装番茄插件
    16年面试提问
    git 使用笔记
    03_运算符、键盘录入、流程控制
    02_java关键字、表识符、注释、进制转换、补码反码、数据类型转换
    01_计算机和java基础
    10 js一维数组、一维数组细节
  • 原文地址:https://www.cnblogs.com/wangshaodong/p/13510900.html
Copyright © 2011-2022 走看看