qsort函数

NAME
qsort, qsort_r - sort an array

SYNOPSIS
#include <stdlib.h>
void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
void qsort_r(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *, void *), void *arg);

DESCRIPTION
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.
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.
The qsort_r() function is identical to qsort() except that the comparison function compar takes a third argument. A pointer is passed to the comparison function via arg. In this way, the comparison function does not need to use global variables to pass through arbitrary arguments, and is therefore reentrant and safe to use in threads.

RETURN VALUE
The qsort() and qsort_r() functions return no value.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int cmp(const void *a, const void *b) 
{
    return strcmp((char* )a, (char* )b);
}

int main(int argc, char** argv) 
{
    char a[6][6] = {"bbb", "cccc", "cc", "eeeee", "aaab", "ddddda"};
    qsort((void*)a, 6, sizeof(a[0]), cmp);
    for(int i=0; i<6; i++)
    {   
        printf("%s\n", a[i]);
    }   
    return 0;
}

运行结果

jl@jl-virtual-machine:~/test$ ./a.out 
aaab
bbb
cc
cccc
dddddaeeeee
eeeee
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值