C programming stdlib.h function - void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void , const void))
The qsort
function is defined in the stdlib.h
header file in C programming language. It is used for sorting an array of elements. The function sorts the elements of an array in ascending order.
The syntax of the qsort
function is as follows:
void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))
The function takes four arguments:
base
: Pointer to the first element of the array to be sorted.nitems
: Number of elements in the array.size
: Size in bytes of each element.compar
: Pointer to a comparison function which takes two arguments of typeconst void*
and returns anint
. The function compares the two elements and returns a negative, zero, or positive value based on their order.
The qsort
function uses a sorting algorithm called QuickSort. The compar
function is called multiple times during the sort, to compare pairs of elements and determine their relative order.
Here's an example of how to use the qsort
function to sort an array of integers in ascending order:
#include <stdlib.h> #include <stdio.h> int compare_ints(const void *a, const void *b) { int arg1 = *(const int *)a; int arg2 = *(const int *)b; if (arg1 < arg2) return -1; if (arg1 > arg2) return 1; return 0; } int main() { int arr[] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5 }; int n = sizeof(arr) / sizeof(int); qsort(arr, n, sizeof(int), compare_ints); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; }
In this example, we define a comparison function compare_ints
that compares two integers and returns a negative value if the first integer is less than the second, a positive value if the first integer is greater than the second, and zero if they are equal. We then pass this function as the compar
argument to the qsort
function, along with the array to be sorted and its size. The qsort
function sorts the array in place, and we then print the sorted array.