qsort的使用

原地址

CPlusPlus


function
<cstdlib>

qsort

void qsort (void* base, size_t num, size_t size,
            int (*compar)(const void*,const void*));
Sort elements of array
Sorts the  num elements of the array pointed to by  base, each element  size bytes long, using the  compar function to determine the order.
对由指针base指向的array数组的num个元素排序,每个元素的大小是size byte使用compar函数来决定顺序。
compar
Pointer 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 to by p1 goes before the element pointed to by p2
0The element pointed to by p1 is equivalent to the element pointed to by p2
>0The element pointed to by p1 goes after the element pointed to by p2

For types that can be compared using regular relational operators, a general  compar function may look like:

1
2
3
4
5
6
int compareMyType (const void * a, const void * b)
{
  if ( *(MyType*)a <  *(MyType*)b ) return -1;
  if ( *(MyType*)a == *(MyType*)b ) return 0;
  if ( *(MyType*)a >  *(MyType*)b ) return 1;
}
 


总结:

qsort第一个参数是指向基地址的指针,第二个参数是要排序的元素的个数,第三个参数是被排序的每个元素的大小,第四个参数是cmp函数,这个函数用来决定排序的顺序
关于cmp函数:由上面的例子可知,如果返回值大于0,a会被移到b的后面。如果小于0,a在b前。可以理解成默认是按降序。具体写法要参照具体情况。
一个例子:(整数数组arr按照升序排列)

int compareMyType (const void * a, const void * b)
{
  if ( *(int*)a >  *(int*)b ) return -1;
  if ( *(int*)a == *(int*)b ) return 0;
  if ( *(int*)a <  *(int*)b ) return 1;
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值