一、qsort()函数
对于较大型的数组而言, “快速排序”方法是最有效的排序算法之一。他把数组不断分成更小的数组。首先把数组分成俩部分,一部分的值都小于另一部分的值,直到排好序。
void qsort(void *base, size_t nmenb, size_t size, int(*compar) (const void *, const void *));
第一个参数是指针,指向待排序数组的首元素。ANSI C允许把指向任何数据类型的指针强制转换成指向void指针。
第二个参数是待排序的数量。
第三个参数表示数组每个元素的大小。
第四个参数是指向函数的指针,这个指针被指向的比较函数用于确定排序的顺序。该函数应接受俩个参数:分别指向带比较两项的指针。如果第一项的值大于第二项,比较函数则返回正数;如果俩项相同,则返回0,如果第一项的值小于第二项,则返回负数。
#include <stdio.h>
#include <stdlib.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()
{
double vals[NUM];
fillarray(vals, NUM);
puts("随机数组:");
showarray(vals, NUM);
qsort(vals, NUM, sizeof(double), mycomp);
puts("\n排序数组:");
showarray(vals, NUM);
return 0;
}
void fillarray(double ar [], int n)
{
int index = 0;
for(index = 0; index < n; index++)
{
ar[index] = (double) rand() / ((double) rand() + 0.1);
}
}
void showarray(const double ar[], int n)
{
int index = 0;
for(index = 0; index < n; index++)
{
printf("%9.4f", ar[index]);
if(index % 6 == 5)
{
putchar('\n');
}
}
if(index % 6 != 1)
{
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;
}
}