max.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <string.h>
  5. static int pile[256];
  6. static int pileQ[256];
  7. static int pileR[256];
  8. #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
  9. __attribute__((pure)) static int compare(const void * restrict p1, const void * restrict p2)
  10. {
  11. int left = *(const int *)p1;
  12. int right = *(const int *)p2;
  13. return (left > right) ? 1 : (left == right) ? 0 : -1;
  14. }
  15. static int is_equal(const int * restrict p1, const int * restrict p2, size_t n)
  16. {
  17. while (n--) {
  18. if (*p1 != *p2)
  19. return -1;
  20. ++p1;
  21. ++p2;
  22. }
  23. return 0;
  24. }
  25. static int get_max(const int *p1, size_t n)
  26. {
  27. int max = *p1;
  28. --n;
  29. ++p1;
  30. while (n--) {
  31. if (max < *p1)
  32. max = *p1;
  33. ++p1;
  34. }
  35. return max;
  36. }
  37. int main()
  38. {
  39. arc4random_buf(pile, sizeof(pile));
  40. clock_t tq0, tq1;
  41. memcpy(pileQ, pile, sizeof pileQ);
  42. memcpy(pileR, pile, sizeof pileR);
  43. qsort(&pileQ, ARRAY_SIZE(pileQ), sizeof(*pileQ), compare);
  44. heapsort(&pileR, ARRAY_SIZE(pileR), sizeof(*pileR), compare);
  45. fputs("000: ", stdout);
  46. for (size_t k = 0; k < ARRAY_SIZE(pileQ); ) {
  47. printf("%16d ", pileQ[k]);
  48. ++k;
  49. if (!(k % 8)) {
  50. puts("");
  51. printf("%03zu: ", k);
  52. }
  53. }
  54. puts("");
  55. printf("sort: %s.\n", is_equal(pileR, pileQ, ARRAY_SIZE(pile)) ? "KO" : "OK");
  56. printf("Max : %d.\n", get_max(pile, ARRAY_SIZE(pile)));
  57. return 0;
  58. }