1 /*---------------------------------------- 2 qsorter.c -- 用 qsort() 排序一组数字 3 ----------------------------------------*/ 4 5 #include <stdio.h> 6 #include <stdlib.h> //提供函数 rand() 原型 7 8 #define NUM 40 9 10 void fillarray(double ar[], int n); 11 void showarray(const double ar[], int n); 12 int mycomp(const void *p1, const void *p2); 13 14 int main() 15 { 16 double vals[NUM]; 17 18 fillarray(vals, NUM); 19 puts("Random list:"); 20 showarray(vals, NUM); 21 22 qsort(vals, NUM, sizeof(double), mycomp); 23 puts(" Sorted list:"); 24 showarray(vals, NUM); 25 26 return 0; 27 } 28 29 void fillarray(double ar[], int n) 30 { 31 for (int index = 0; index != n; ++index) 32 ar[index] = (double)(rand()) / ((double)(rand()) + 0.1); 33 } 34 35 void showarray(const double ar[], int n) 36 { 37 int index = 0; 38 39 for (; index != n; ++index) 40 { 41 printf("%9.4f ", ar[index]); 42 if (index % 6 == 5) putchar(' '); 43 } 44 45 if (index % 6 != 0) putchar(' '); 46 } 47 48 int mycomp(const void *p1, const void *p2) 49 { 50 const double *a1 = (double*)p1; 51 const double *a2 = (double*)p2; 52 53 if (*a1 > *a2) 54 return 1; 55 else if (*a1 == *a2) 56 return 0; 57 else 58 return -1; 59 }