使用比较器调用 qsort
标准库回调
使用比较器调用 qsort 是 CoddyKit 上的免费 C Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 C Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 C Academy 课程共包含 4 节课。
标准 qsort
标准库在<stdlib.h>中提供了qsort。它通过使用比较器回调函数,对任意数组类型进行通用排序。
#include <stdio.h>
#include <stdlib.h>
int cmp_int(const void *a, const void *b) {
int x = *(const int *)a;
int y = *(const int *)b;
return (x > y) - (x < y);
}
int main(void) {
int a[] = {3, 1, 2};
qsort(a, 3, sizeof(int), cmp_int);
printf("%d %d %d\n", a[0], a[1], a[2]);
return 0;
}qsort 的签名
qsort(base, count, size, compare)接收数组起始地址、元素数量、元素大小和比较器。
它之所以通用,是因为它处理原始字节,并使用您提供的比较器。
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
return *(const int*)a - *(const int*)b;
}
int main(void) {
int a[] = {9, 4, 7, 1};
qsort(a, 4, sizeof(int), cmp);
for (int i = 0; i < 4; i++) printf("%d ", a[i]);
printf("\n");
return 0;
}比较器约定
如果第一个元素应排在第二个元素之前,比较器返回负数;如果两者相等,返回零;如果应排在后面,返回正数。
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
int x = *(const int*)a, y = *(const int*)b;
if (x < y) return -1;
if (x > y) return 1;
return 0;
}
int main(void) {
int a[] = {5, 2, 8, 2};
qsort(a, 4, sizeof(int), cmp);
for (int i = 0; i < 4; i++) printf("%d ", a[i]);
printf("\n");
return 0;
}转换 void 指针
比较器会为每个元素接收一个const void *。请将它们转换为正确的类型,然后解引用以读取值。
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
double x = *(const double*)a;
double y = *(const double*)b;
return (x > y) - (x < y);
}
int main(void) {
double d[] = {2.5, 1.1, 3.3};
qsort(d, 3, sizeof(double), cmp);
printf("%.1f %.1f %.1f\n", d[0], d[1], d[2]);
return 0;
}降序排列
反转比较结果,即可按从大到小的顺序排序。
#include <stdio.h>
#include <stdlib.h>
int desc(const void *a, const void *b) {
int x = *(const int*)a, y = *(const int*)b;
return (y > x) - (y < x);
}
int main(void) {
int a[] = {1, 5, 3, 2};
qsort(a, 4, sizeof(int), desc);
for (int i = 0; i < 4; i++) printf("%d ", a[i]);
printf("\n");
return 0;
}避免减法溢出
返回x - y可能会在整数较大时溢出。安全写法(x > y) - (x < y)可以避免这一问题。
#include <stdio.h>
#include <stdlib.h>
int safe_cmp(const void *a, const void *b) {
int x = *(const int*)a, y = *(const int*)b;
return (x > y) - (x < y);
}
int main(void) {
int a[] = {100, -100, 0};
qsort(a, 3, sizeof(int), safe_cmp);
for (int i = 0; i < 3; i++) printf("%d ", a[i]);
printf("\n");
return 0;
}排序字符串
对于char *数组,每个元素本身都是一个指针,因此应转换为const char * const *,并使用strcmp进行比较。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp_str(const void *a, const void *b) {
const char *sa = *(const char * const *)a;
const char *sb = *(const char * const *)b;
return strcmp(sa, sb);
}
int main(void) {
const char *w[] = {"pear", "apple", "fig"};
qsort(w, 3, sizeof(char*), cmp_str);
for (int i = 0; i < 3; i++) printf("%s ", w[i]);
printf("\n");
return 0;
}排序结构体
qsort 同样可以处理结构体数组。在比较器中比较选定的字段即可。
#include <stdio.h>
#include <stdlib.h>
typedef struct { char name; int age; } Person;
int by_age(const void *a, const void *b) {
int x = ((const Person*)a)->age;
int y = ((const Person*)b)->age;
return (x > y) - (x < y);
}
int main(void) {
Person p[] = {{'C',30},{'A',20},{'B',25}};
qsort(p, 3, sizeof(Person), by_age);
for (int i = 0; i < 3; i++) printf("%c:%d ", p[i].name, p[i].age);
printf("\n");
return 0;
}bsearch 使用相同思想
bsearch使用与qsort相同的比较器约定,在有序数组中执行二分搜索。
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
return (*(const int*)a) - (*(const int*)b);
}
int main(void) {
int a[] = {1, 3, 5, 7, 9};
int key = 7;
int *found = bsearch(&key, a, 5, sizeof(int), cmp);
printf("found: %d\n", found ? *found : -1);
return 0;
}多个排序键
比较器可以先比较主要字段;如果主要字段相同,再比较次要字段。
#include <stdio.h>
#include <stdlib.h>
typedef struct { int grade; int id; } Rec;
int cmp(const void *a, const void *b) {
const Rec *x = a, *y = b;
if (x->grade != y->grade) return x->grade - y->grade;
return x->id - y->id;
}
int main(void) {
Rec r[] = {{90,2},{90,1},{80,3}};
qsort(r, 3, sizeof(Rec), cmp);
for (int i = 0; i < 3; i++) printf("%d/%d ", r[i].grade, r[i].id);
printf("\n");
return 0;
}通用排序为何重要
由于qsort将算法与比较逻辑分离,一个经过充分测试的函数就能对任何可比较的数据类型进行排序。
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
char x = *(const char*)a, y = *(const char*)b;
return (x > y) - (x < y);
}
int main(void) {
char s[] = "dcba";
qsort(s, 4, sizeof(char), cmp);
printf("%s\n", s);
return 0;
}快速检查
请检验您对 qsort 比较器的理解。
回顾
您已经学会了使用带比较器的 qsort:
qsort(base, count, size, compare)可以以通用方式对任意数组排序。- 比较器接收两个
const void *,并返回负数、零或正数。 - 使用
(x > y) - (x < y)避免溢出。 - 相同的比较器约定也适用于
bsearch、结构体排序和多键排序。
常见问题解答
「使用比较器调用 qsort」课时是免费的吗?
是的 — 「使用比较器调用 qsort」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 C Academy 课程的其余内容,请升级到 CoddyKit PRO。 C Academy 课程共包含 4 节课。
「使用比较器调用 qsort」这节课中我会学到什么?
标准库回调 你通过在浏览器中直接运行的动手代码来练习 C Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 C Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 C Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「使用比较器调用 qsort」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 C Academy 课中编写并运行代码吗?
能。每节 C Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。