qsort函数

本文详细介绍了C语言标准库中的排序函数qsort和qsort_r,包括它们的使用语法、功能以及如何定义比较函数。通过一个字符串数组排序的示例,展示了qsort函数的使用,排序后打印出结果。qsort_r函数增加了传递额外参数的能力,使其在多线程环境中更安全。

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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值