How to use the sort function in the C language?
In C language, you can use the qsort function from the stdlib.h header file to perform sorting operations.
The prototype of the qsort function is as follows:
void qsort(void* base, size_t num, size_t size, int (*compar)(const void*, const void*));
Parameter description:
- Pointer base pointing to the first element of the array to be sorted.
- num: the number of elements in the array.
- size: the size of each element, measured in bytes.
- compar: a pointer to a function used to compare two elements.
The prototype of the comparison function compar is as follows:
int compar(const void* a, const void* b);
The comparison function should return an integer value indicating the relationship between a and b. It should return a negative number if a is less than b, 0 if they are equal, and a positive number if a is greater than b.
Here is an example of sorting using the qsort function:
#include <stdio.h>
#include <stdlib.h>
// 比较函数,按照从小到大的顺序排序
int compare(const void* a, const void* b) {
return (*(int*)a - *(int*)b);
}
int main() {
int arr[] = {5, 2, 8, 1, 6};
int n = sizeof(arr) / sizeof(arr[0]);
qsort(arr, n, sizeof(int), compare);
printf("排序后的数组:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Result of execution:
排序后的数组:1 2 5 6 8
In this code snippet, a comparison function called compare is first defined to sort in ascending order. Then, an integer array called arr is declared and sorted using the qsort function. Finally, the sorted result is outputted.