+ 2
Can someone explain me this code
High level sorting through pointers #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; }
4 Answers
+ 3
qsort() is an implementation of the quicksort algorithm and is used to sort an array:
http://www.cplusplus.com/reference/cstdlib/qsort/
In order to sort the given array, the algorithm needs to compare the elements inside to determine how they should be ordered. The comparison is done via a function ( here: compare() ) specified by the user, to enable the algorithm working for user-defined types and more:
https://www.geeksforgeeks.org/comparator-function-of-qsort-in-c/
+ 2
What is compare and qshort functions doing...???
+ 1
You can always find explanations of standard methods and classes on the developers website. Same for APIs, external libraries - but here it depends on the comment style of the author. That's why you should comment your code with javadoc, etc. if possible, so that others will understand your posted code snippets :)