+ 1
Explain it how this rearrange value increasing order
#include <stdio.h> #include <stdlib.h> int compare (const void *, const void *); int main() { int arr[5] = {52, 23, 56, 19, 4}; int num, width, i; num = sizeof(arr)/sizeof(arr[0]); width = sizeof(arr[0]); qsort((void *)arr, num, width, compare); for (i = 0; i < 5; i++) printf("%d ", arr[ i ]); return 0; } int compare (const void *elem1, const void *elem2) { if ((*(int *)elem1) == (*(int *)elem2)) return 0; else if ((*(int *)elem1) < (*(int *)elem2)) return -1; else return 1; }
1 ответ
+ 1
The builtin function qsort implements the qsort algorithm. To sort anything, all you need to know is how to compare two items. That is what the compare function is for that is passed to the qsort algorithm as argument.
A comparison function essentially returns three possible values: equal, less than, or greater than. C does not have a specific type for that - it encodes this information as integers. A negative result means a < b, 0 means a is equal to b, and finally a positive result means a > b. So, technically, your compare function can be (and would be) shortened to
int compare(void *a, void *b) {
return ( *(int*)a - *(int*)b );
}