+ 1
Anyone explain this code??
#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 Respostas
+ 4
int main() {
int arr[5] = {52, 23, 56, 19, 4};
int num, width, i;
// calculate number of array elements
num = sizeof(arr)/sizeof(arr[0]);
// measure size of a single array element
width = sizeof(arr[0]);
// sort the array, using the algorithm
// implemented in compare function
// Reference:
// https://en.cppreference.com/w/c/algorithm/qsort
qsort((void *)arr, num, width, compare);
// display sorted array contents
for (i = 0; i < 5; i++)
printf("%d ", arr[ i ]);
return 0;
}
// sort function that supplies a value
// used by qsort to decide whether
// <elem1> was less, equal, or greater
// compared to <elem2>
int compare (const void *elem1, const void *elem2) {
if ((*(int *)elem1) == (*(int *)elem2))
return 0;
// return 0 if <elem1> equals <elem2>
else if ((*(int *)elem1) < (*(int *)elem2))
return -1;
// return -1 if <elem1> is less than <elem2>
else
return 1;
// return 1 if <elem1> is greater than <elem2>
}
+ 3
You're welcome, glad if it helps 👍
+ 2
This sorts the array arr and prints it.
+ 1
Thankyou for the explanation Ipang