In this source code example, we will see how to use the qsort() function in C programming with an example.
qsort() Function Overview
The qsort() function is found in the <stdlib.h> header file and it is used to sort elements in an array. This function is versatile, as it can be used to sort arrays of any data type. The sorting is performed using the quicksort algorithm.
Source Code Example
#include <stdio.h>
#include <stdlib.h>
// Comparison function for integers
int compare(const void *a, const void *b) {
return (*(int *)a - *(int *)b);
}
int main() {
int values[] = {40, 10, 100, 90, 20, 25};
// Number of elements in the array
int size = sizeof(values)/sizeof(values[0]);
printf("Before sorting: ");
for(int i=0; i < size; i++) printf("%d ", values[i]);
// Using qsort() to sort the array
qsort(values, size, sizeof(int), compare);
printf("\nAfter sorting: ");
for(int i=0; i < size; i++) printf("%d ", values[i]);
return 0;
}
Output
Before sorting: 40 10 100 90 20 25 After sorting: 10 20 25 40 90 100
Explanation
1. We start by defining an array values which contains a set of unsorted integers.
2. A comparison function compare is defined. This function is essential for the qsort() function to determine the order of elements.
3. We calculate the number of elements in the array using sizeof.
4. The array before sorting is printed.
5. We then call the qsort() function, providing it with the array, number of elements, size of each element, and our comparison function.
6. After sorting, the sorted array is printed.
Comments
Post a Comment