C/C++ 标准库<stdlib.h> 包含qsort 函数。
这不是世界上最好的快速排序实现,但它足够快而且非常
易于使用... qsort 的正式语法是:
qsort(<arrayname>,<size>,sizeof(<elementsize>),compare_function);
您唯一需要实现的是 compare_function,它包含两个
“const void”类型的参数,可以转换为适当的数据结构,然后
返回以下三个值之一:
- 否定,如果 a 应该在 b 之前
- 0,如果 a 等于 b
- 肯定的,如果 a 应该在 b 之后
1.比较整数列表:
只需将 a 和 b 转换为整数
如果x < y,x-y 为负,x == y,x-y = 0,x > y,x-y 为正
x-y 是一种捷径:)
将*x - *y 反转为*y - *x,用于按降序/倒序排序
int compare_function(const void *a,const void *b) {
int *x = (int *) a;
int *y = (int *) b;
return *x - *y;
}
2。比较字符串列表:
为了比较字符串,你需要 <string.h> 库中的 strcmp 函数。
strcmp 默认情况下会适当地返回 -ve,0,ve... 以相反的顺序排序,只需反转 strcmp 返回的符号
#include <string.h>
int compare_function(const void *a,const void *b) {
return (strcmp((char *)a,(char *)b));
}
3.比较浮点数:
int compare_function(const void *a,const void *b) {
double *x = (double *) a;
double *y = (double *) b;
// return *x - *y; // this is WRONG...
if (*x < *y) return -1;
else if (*x > *y) return 1; return 0;
}
4.根据键比较记录:
有时您需要对更复杂的东西进行排序,例如记录。这里是最简单的
使用qsort 库的方法。
typedef struct {
int key;
double value;
} the_record;
int compare_function(const void *a,const void *b) {
the_record *x = (the_record *) a;
the_record *y = (the_record *) b;
return x->key - y->key;
}