理解qsort 中的 cmp

本文详细解析了qsort函数中比较函数cmp的作用原理。通过对比两个元素指针所指向的内容,cmp函数定义了元素间的顺序,返回值决定了排序方向。文章还提供了升序与降序排列的具体实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

百度了很多的资料都没有明白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
<0The element pointed by p1 goes before the element pointed by p2
0The element pointed by p1 is equivalent to the element pointed by p2
>0The 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

转载于:https://www.cnblogs.com/been/p/4470199.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值