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);

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

   qsort_r(): _GNU_SOURCE

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
上一篇:qsort函数


下一篇:利用qsort函数排序结构体