C Library Function - qsort()
Description
qsort is a function provided by the C standard library used to perform a quicksort on an array. It is defined in header file.qsort It uses the quicksort algorithm, which is an efficient sorting algorithm with an average time complexity of O(n log n).
C Library Function **void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void , const void)) ** sorts an array.
Declaration
The following is the declaration of the qsort() function.
void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *));
Parameters
base: A pointer to the first element of the array to be sorted.nitems: The number of elements in the array.size: The size of each element in the array (in bytes).compar: A pointer to a comparison function used to compare two elements. The comparison function should return an integer indicating the comparison result:- Less than zero: indicates the first element is less than the second.
- Equal to zero: indicates the two elements are equal.
- Greater than zero: indicates the first element is greater than the second.
Return Value
This function does not return any value.
Example
The following example demonstrates the use of the qsort() function.
Example
#include
#include
// Define an array containing five integers
int
values
[
]
=
{
88
,
56
,
100
,
2
,
25
}
;
// Comparison function, used to compare two integers
int
cmpfunc
(
const
void
a
,
const
void
b
)
{
return
(
(
int
)
a
(
int
)
b
)
;
}
int
main
(
)
{
int
n
;
// Output the array contents before sorting
printf
(
"list before sorting:\n"
)
;
for
(
n
=
0
;
n
<
5
;
n
++
)
{
printf
(
"%d "
,
values
[
n
]
)
;
}
// Use the qsort function to sort the array
qsort
(
values
,
5
,
sizeof
(
int
)
,
cmpfunc
)
;
// Output the array contents after sorting
printf
(
"\nlist after sorting:\n"
)
;
for
(
n
=
0
;
n
<
5
;
n
++
)
{
printf
(
"%d "
,
values
[
n
]
)
;
}
return
0
;
}
Let's compile and run the above program, which will produce the following result:
List before sorting:
88 56 100 2 25
Sorted list:
2 25 56 88 100
C Standard Library -