/*----------------------------------------
qsorter.c -- 用 qsort() 排序一组数字
----------------------------------------*/ #include <stdio.h>
#include <stdlib.h> //提供函数 rand() 原型 #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("Random list:");
showarray(vals, NUM); qsort(vals, NUM, sizeof(double), mycomp);
puts("\nSorted list:");
showarray(vals, NUM); return ;
} void fillarray(double ar[], int n)
{
for (int index = ; index != n; ++index)
ar[index] = (double)(rand()) / ((double)(rand()) + 0.1);
} void showarray(const double ar[], int n)
{
int index = ; for (; index != n; ++index)
{
printf("%9.4f ", ar[index]);
if (index % == ) putchar('\n');
} if (index % != ) putchar('\n');
} int mycomp(const void *p1, const void *p2)
{
const double *a1 = (double*)p1;
const double *a2 = (double*)p2; if (*a1 > *a2)
return ;
else if (*a1 == *a2)
return ;
else
return -;
}
qsorter.c