The qsort function is a library function in C language, used to sort arrays. Although the qsort function is very general and can handle any type of array, the comparison function can become complex, especially when dealing with complex data structures.
The qsort function is a library function in C language that is used to sort arrays. It is defined in the
void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*));
Here is the parameter description of the qsort function:
base: points to the first element of the array to be sorted Pointer to the object.
nitems: The number of elements in the array.
size: The size of each element is usually obtained using the sizeof operator.
compar: A comparison function used to determine the order of two elements. This function should accept two pointers, pointing to the elements to be compared, and return a negative number if the first element is less than the second, 0 if they are equal, and a positive number if the first element is greater than the second.
This is an example of using the qsort function, which sorts an array of integers:
#include <stdio.h> #include <stdlib.h> // 比较函数,用于决定排序 int compare(const void *a, const void *b) { int int_a = *((int*) a); int int_b = *((int*) b); if (int_a == int_b) return 0; else if (int_a < int_b) return -1; else return 1; } int main() { int i; int numbers[] = {7, 3, 4, 1, -1, 23, 12, 43, -8, 5}; int size = sizeof(numbers) / sizeof(int); // 对数组进行排序 qsort(numbers, size, sizeof(int), compare); // 输出排序后的数组 for(i = 0; i < size; i++) { printf("%d ", numbers[i]); } return 0; }
Note: Although the qsort function is very general and can handle any type of array , but its comparison functions can get complicated, especially when you're dealing with complex data structures. When writing a comparison function, make sure it works as you expect.
The above is the detailed content of How to use the qsort function. For more information, please follow other related articles on the PHP Chinese website!