C中的快速排序函数原型:
void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
第1个参数是指针,指向待排序数组的首元素。ANSI C允许把指向任何数据类型的指针强制转换成指向void的指针,因此,qsort()的第1个实际参数可以引用任何类型的数组。
第2个参数是待排序项的数量。函数原型把该值转换为size_t类型。size_t定义在标准头文件中,是sizeof运算符返回的整数类型。
由于qsort()把第1个参数转换为void指针,所以qsort()不知道数组中每个元素的大小。为此,函数原型用第3个参数补偿这一信息,显式指明待排序数组中每个元素的大小。例如,如果排序double类型的数组,那么第3个参数应该是sizeof(double)。
示例
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
//#include <stdbool.h> //C99特性
//#include <string.h>
//#include <math.h>
//#include <ctype.h>
//#include <tgmath.h>
#define NUM 40
void fillarray(double ar [], int n);
void showarray(const double ar[], int n);
int mycomp(const void* p1, const void* p2);
int main(int argc, char* argv[])
{
double vals[NUM];
fillarray(vals, NUM);
puts("Random list:");
showarray(vals, NUM);
qsort(vals, NUM, sizeof(double), mycomp);
puts("\nSorted list:");
showarray(vals, NUM);
system("pause");
return 0; //main()函数退出时会隐式调用exit()
}
void fillarray(double ar[], int n)
{
int index;
for (index = 0; index < n; index++)
ar[index] = (double)rand() / ((double)rand() + 0.01);
}
void showarray(const double ar[], int n)
{
int index;
for (index = 0; index < n; index++)
{
printf("%9.4f ", ar[index]);
if (index % 6 == 5)
putchar('\n');
}
if (index % 6 != 0)
putchar('\n');
}
/* 按从小到大的顺序排序 */
int mycomp(const void* p1, const void* p2)
{
/* 要使用指向double的指针来访问这两个值 */
const double* a1 = (const double*)p1;
const double* a2 = (const double*)p2;
if (*a1 < *a2)
return -1;
else if (*a1 == *a2)
return 0;
else
return 1;
//或者
//return *(double*)p1 < *(double*)p2 ? -1 : 1;
//如果是比较字符串,可以使用strcmp()函数
}