qsorter.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* qsorter.c -- using qsort to sort groups of numbers */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #define NUM 40
  5. void fillarray(double ar[], int n);
  6. void showarray(const double ar[], int n);
  7. int mycomp(const void * p1, const void * p2);
  8. int main(void)
  9. {
  10. double vals[NUM];
  11. fillarray(vals, NUM);
  12. puts("Random list:");
  13. showarray(vals, NUM);
  14. qsort(vals, NUM, sizeof(double), mycomp);
  15. puts("\nSorted list:");
  16. showarray(vals, NUM);
  17. return 0;
  18. }
  19. void fillarray(double ar[], int n)
  20. {
  21. int index;
  22. for( index = 0; index < n; index++)
  23. ar[index] = (double)rand()/((double) rand() + 0.1);
  24. }
  25. void showarray(const double ar[], int n)
  26. {
  27. int index;
  28. for( index = 0; index < n; index++)
  29. {
  30. printf("%9.4f ", ar[index]);
  31. if (index % 6 == 5)
  32. putchar('\n');
  33. }
  34. if (index % 6 != 0)
  35. putchar('\n');
  36. }
  37. /* sort by increasing value */
  38. int mycomp(const void * p1, const void * p2)
  39. {
  40. /* need to use pointers to double to access values */
  41. const double * a1 = (const double *) p1;
  42. const double * a2 = (const double *) p2;
  43. if (*a1 < *a2)
  44. return -1;
  45. else if (*a1 == *a2)
  46. return 0;
  47. else
  48. return 1;
  49. }