Example of qsort() in C
Input:
arr = [4, 2, 5, 3, 1]
Output:
Sorted Array: 1 2 3 4 5
The below program demonstrates how we can sort a given array using qsort() function in C.
// C Program to sort an array using qsort() function in C
#include <stdio.h>
#include <stdlib.h>
// Comparison function
int compare(const void* a, const void* b)
{
return (*(int*)a - *(int*)b);
}
int main()
{
int arr[] = { 4, 2, 5, 3, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
qsort(arr, n, sizeof(int), compare);
printf("Sorted array: \n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output
Sorted array: 1 2 3 4 5
Time Complexity: O(n log n), where n is the number of elements in the array.
Auxilliary Space: O(log n), due to the stack space used by the recursive calls.
qsort() Function in C
The qsort()
function in C is a predefined function in the stdlib.h
library that is used to sort an array of items in ascending order or descending order. It stands for “quick sort,” as it implements the quicksort algorithm for sorting which is one of the fastest and most efficient algorithm to sort elements of an array.