qsort() - Utility Function
How is Utility function "qsort()" used in C++?
How to Sort the Elements of the Array?
Explanation
qsort() is a Utility Function that is used to quick sort an array. The "size", number of elements ("num") is specified in this function.
Syntax:
void qsort(void *buf, size_t num, size_t size,
int (*compare) (const void *, const void *));
In the above syntax "compare" is used to compare the elements with a keys of an array. This function returns "0" if both arguments are equal, if "arg1" is less than "arg2" the a negative value is returned. If "arg1" is greater then a positive value is returned by the function. The following is the syntax of this function.
Syntax:
int func_name(const void *arg1, const void *arg2);
Example :
#include <stdlib.h> #include <stdio.h> #include <string.h> int main () { int i; char arr[3][20] = {"2", "1", "3" }; qsort(arr,3, 20, (int(*) (const void*, const void*))strcmp); printf("The sorted array\n"); for (i=0; i<3; ++i) printf ("%s\n", arr[i]); return 0; } |
Result :
The sorted array
1
2
3
In the above example qsort() function is used to sort the array in descending order.