0

how this qsort working?

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

21st Jun 2020, 2:52 AM
Harshit Nema
Harshit Nema - avatar
2 Antworten
0
qsort requires an argument as function. In this case the function is compare. What compare is doing is taking two arguements if the first one is bigger, smaller or equal to the second number. qsort iterates through the array checking two numbers at a time using compare function.
21st Jun 2020, 3:16 AM
XXX
XXX - avatar
0
That's what I want to know how the iteration is happening?
21st Jun 2020, 3:42 AM
Harshit Nema
Harshit Nema - avatar