zoukankan      html  css  js  c++  java
  • 理解qsort 中的 cmp

    百度了很多的资料都没有明白qsort 中 cmp 的用处,用Bing 一搜就搜到一篇自认为比其他都解析清楚的文章

    直接贴出来算了

    comparPointer to a function that compares two elements.
    This function is called repeatedly by qsort to compare two elements. It shall follow the following prototype:

     
    int compar (const void* p1, const void* p2);
     


    Taking two pointers as arguments (both converted to const void*). The function defines the order of the elements by returning (in a stable and transitive manner):

    return valuemeaning
    <0 The element pointed by p1 goes before the element pointed by p2
    0 The element pointed by p1 is equivalent to the element pointed by p2
    >0 The element pointed by p1 goes after the element pointed by p2

    假如你要按升序排列数组,需要处理两个参数P1 ,P2,如果P1 > P2 ,那cmp需要返回的是一个<0的值,所以是P1-P2

    若P1<P2 ,那么cmp需要返回一个 >0的值,所以同样是P1-P2,一点都不矛盾。

    假如你要按降序排列数组,需要处理两个参数P1 ,P2,如果P1 > P2 ,排序应该是P1在P2前面,那cmp需要返回的是一个<0的值,所以是P2-P1 ,若P1<P2 ,那么cmp需要返回一个 >0的值,所以同样是P2-P1

  • 相关阅读:
    数据库之事务与常见故障
    数学的魅力 之 正多边形
    html5 的基础理解1
    android 引入开源项目
    android 图片查看器
    java 线程安全
    python3 自动生成requirement.txt
    centos 7 安装 python3.7
    python3 创建,激活虚拟环境
    Mac 配置poetry
  • 原文地址:https://www.cnblogs.com/been/p/4470199.html
Copyright © 2011-2022 走看看