stdlib 头文件中的排序函数 qsort
1.函数原型
void qsort( void *ptr, size_t count, size_t size,
int (*comp)(const void *, const void *) );
- ptr 指向待排序数组的指针
- count 待排序数组的长度
- size 待排序数组元素的大小,可以使用
sizeof(elemType)
求得 - comp 描述比较规则的函数,该函数形式为:
int cmp(const void *a, const void *b);
2.描述比较规则的函数
比较函数不能修改其传入的参数的内容,对于同样的对象不管他们在数组中的位置如何,必须能够返回一致的结果。
比较函数内描述的是一个规则,这个规则构建好之后,就可以让数组中的数据按照此规则排列。比较函数的具体内容可以根据自己的需要进行构造,不一定非得是数值大小的比较,同样,进行比较的内容也就不会限定在数字,也可以是字符、字符串、结构体。
比较函数形式如下:
int cmp(const void *a, const void *b);
- 参数,两个 void 类型的指针,在使用的时候需要现对其进行强制类型转换,再解引用
- 返回值,按照定义的的比较逻辑分别返回 1, 0, -1
以下通过示例介绍比较规则函数的使用方法:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 定义一个结构体类型
typedef struct S{
int first;
int second;
char third;
}S;
// 定义比较规则函数
int compare(const void* a, const void* b) {
// 这里需要将参数传入的 void 类型的指针强制转换为我们需要的类型,之后再解引用
struct S s1 = *(struct S*)a;
struct S s2 = *(struct S*)b;
// 之后我们就可以访问到我们需要的数据,并在某个数据上定义比较规则
if (s1.second > s2.second)
return 1;
else if (s1.second < s2.second)
return -1;
return 0;
}
// 用于打印结构体的内容
void print(struct S s) {
printf("first: %d, second: %d, third: %c\n", s.first, s.second, s.third);
}
int main() {
struct S s[5];
srand((unsigned)time(NULL));
// 随机生成结构体的数据
for (int i = 0; i < 5; i++) {
s[i].first = rand() % 100;
s[i].second = rand() % 200;
s[i].third = i + '0';
}
// 打印出结构体的内容
for (int i = 0; i < 5; i++) {
print(s[i]);
}
// 排序
qsort(s, 5, sizeof(struct S), compare);
printf("--------分割线--------\n");
// 再次打印结构体的内容
for (int i = 0; i < 5; i++) {
print(s[i]);
}
return 0;
}
/*
运行程序,得到结果如下:
first: 90, second: 63, third: 0
first: 95, second: 11, third: 1
first: 14, second: 169, third: 2
first: 9, second: 3, third: 3
first: 14, second: 198, third: 4
--------分割线--------
first: 9, second: 3, third: 3
first: 95, second: 11, third: 1
first: 90, second: 63, third: 0
first: 14, second: 169, third: 2
first: 14, second: 198, third: 4
可以看到结构体数组中的内容,按照第二个整形元素 second 的大小进行了升序排列
*/
3. 总结
弄清楚 qsort 函数的参数列表,学会比较规则函数的定义方法,就可以很方便的对诸多类型的数组进行排序了。