C stdlib qsort() 函数
示例
对数组进行排序
// Comparing function:
// Returns a positive number if a is greater than b
// Returns a negative number if a is less than b
// Returns 0 if a is equal to b
int compare(const void *a, const void *b) {
int *valA = a;
int *valB = b;
return *valA - *valB;
}
int main() {
// Create an array
int myArray[] = {20, 32, 5, 2, 24, 15};
int size = sizeof(myArray) / sizeof(myArray[0]);
// Sort the values in the array
qsort (myArray, size, sizeof(myArray[0]), compare);
// Display the values of the array
for(int i = 0; i < size; i++) {
printf("%d ", myArray[i]);
}
return 0;
}
自己动手试一试 »
定义和用法
qsort()
函数将数组中的元素从最少到最多进行排序。
qsort()
函数定义在 `<stdlib.h>
` 头文件中。
语法
qsort(void * arr, size_t amount, size_t size, compare);
size_t
数据类型是一个非负整数。
参数值
参数 | 描述 |
---|---|
arr | 必需。指定要排序的数组。 |
amount | 必需。指定数组中元素的数量。 |
大小 | 必需。以字节为单位指定数组中元素的长度。 |
比较 | 必需。指定一个函数,用于比较数组中的一对元素,以确定哪个更大。 该函数应具有结构 int myFunction(const void * a, const void * b) ,其中参数 a 和 b 是正在比较的数组元素的指针。如果 a 大于 b,该函数应返回正数;如果 a 小于 b,则返回负数;如果 a 等于 b,则返回零。 |