c sort function in library: qsort()

目錄

qsort() in C library

example

reference


qsort() in C library

Usually sort is the first step for an algorithm. In C, there is one library function for sort: qsort.

It's prototype and introduction from man page as following,

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

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.

So if you need a ascending order, compar function need return >0, ==0 , <0 if the 1st arg >, = , < the 2nd arg. If you need a descending order, compar function need return <0, ==0 , >0 if the 1st arg >, = , < the 2nd arg.

example

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

// void qsort(void *base, size_t nmemb, size_t size,
//          int (*cmp)(const void *, const void *));

int cmp(const void *v1, const void *v2)
{
    int t1 = *(int *)v1;
    int t2 = *(int *)v2;

    // ascending
    //return (t1 > t2) - (t1 < t2);

    // descending
    return (t1 < t2) - (t1 > t2);
}

int main()
{
    int a[10] = {3, 4, 5, 8, 1, 2, 6};
    int len = 7;

    int i;
    for (i = 0; i < len; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");

    qsort(a, len, sizeof(a[0]), cmp);

    for (i = 0; i < len; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");
}

About cmp(), return (t1 > t2) - (t1 < t2); is for avoiding overflow. see stackoverflow for an explanation.

reference

https://stackoverflow.com/questions/1787996/c-library-function-to-perform-sort

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章