This shows you the differences between two versions of the page.
c:stdlib.h:qsort [2013/01/22 22:02] |
c:stdlib.h:qsort [2024/02/16 01:04] (current) |
||
---|---|---|---|
Line 1: | Line 1: | ||
+ | {{keywords>wiki library source code example reference}} | ||
+ | ====== qsort ====== | ||
+ | |||
+ | <code c> | ||
+ | #include <stdlib.h> | ||
+ | void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*)); | ||
+ | </code> | ||
+ | |||
+ | ===== Description ===== | ||
+ | |||
+ | base = Pointer to elements\\ | ||
+ | nitems = Number of elements\\ | ||
+ | size = Size of one element\\ | ||
+ | compar = Pointer to comparison function\\ | ||
+ | |||
+ | |||
+ | qsort will sort an array of elements\\ | ||
+ | with using a comparison function\\ | ||
+ | |||
+ | |||
+ | ===== qsort C Sourcecode Example ===== | ||
+ | |||
+ | <code c> | ||
+ | /* | ||
+ | * qsort example code | ||
+ | * http://code-reference.com/c/stdlib.h/qsort | ||
+ | */ | ||
+ | |||
+ | #include <stdio.h> | ||
+ | #include <stdlib.h> | ||
+ | |||
+ | int compare(const int *n1, const int *n2) | ||
+ | { | ||
+ | if (*n1 == *n2) { return 0; } | ||
+ | else if (*n1 < *n2) { return -1; } | ||
+ | else if (*n1 > *n2) { return 1; } | ||
+ | else | ||
+ | return 0; | ||
+ | } | ||
+ | |||
+ | |||
+ | int main( void ) | ||
+ | { | ||
+ | int array[]= {42,43,44,5,23,992,1231,3133,3,9274}; | ||
+ | int i; | ||
+ | |||
+ | for (i=0; i<10; i++){ | ||
+ | printf ("%d ",array[i]); | ||
+ | } | ||
+ | printf(" not sorted\n"); | ||
+ | qsort(array, 10, sizeof(int), (void *)compare ); | ||
+ | |||
+ | for (i=0; i<10; i++){ | ||
+ | printf ("%d ",array[i]); | ||
+ | } | ||
+ | printf(" Sorted with qsort\n"); | ||
+ | |||
+ | return 0; | ||
+ | } | ||
+ | </code> | ||
+ | |||
+ | ==== output of qsort example ==== | ||
+ | user@host:~/code-reference.com# ./qsort | ||
+ | 42 43 44 5 23 992 1231 3133 3 9274 not sorted | ||
+ | 3 5 23 42 43 44 992 1231 3133 9274 Sorted with qsort | ||
+ | |||
+ | |||
+ | |||
+ | |||