fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <string.h>
  5. int *shuffle(int *a, int size) {
  6. int i, j, ai;
  7. for (i = size - 1; i > 0; i--) {
  8. j = rand() % i;
  9. ai = a[i];a[i] = a[j];a[j] = ai;
  10. }
  11. return a;
  12. }
  13. int *_ia(int first, int last) {
  14. int i, len = 1 + last - first, *a;
  15. if (last < first || len < 1) return 0;
  16.  
  17. a = malloc(sizeof (int) * len);
  18. for (i = 0; i < len; i++) a[i] = first + i;
  19. return a;
  20. }
  21. int icmp(const void *a, const void *b){
  22. return *(int *)a - *(int *)b;
  23. }
  24.  
  25. void *dup(const void *src, size_t nel, size_t width) {
  26. void *dst = malloc(nel * width);
  27. memcpy(dst, src, nel * width);
  28. return dst;
  29. }
  30. clock_t check(
  31. void (*sort)(void *, size_t, size_t, int (*)())
  32. , const void *src, size_t nel, size_t width
  33. , int (*compar)(const void *, const void *)
  34. ) {
  35. clock_t start, end;
  36. void *base = dup(src, nel, width);
  37. start = clock();
  38. sort(base, nel, width, compar);
  39. end = clock();
  40. free(base);
  41. return (end - start);
  42. }
  43. void swap(char *a, char *b, unsigned width) {
  44. char tmp;
  45. if (a != b) {
  46. while (width--) {
  47. tmp = *a;
  48. *a++ = *b;
  49. *b++ = tmp;
  50. }
  51. }
  52. }
  53. void bubble_sort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)) {
  54. int i, j;
  55. for (i = 0; i < nmemb - 1; i++) {
  56. for (j = i + 1; j < nmemb; j++) {
  57. if (compar(base + size * i, base + size * j) > 0) {
  58. swap(base + size * i, base + size * j, size);
  59. }
  60. }
  61. }
  62. }
  63. void comb_sort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)) {
  64. int h = nmemb * 10 / 13, i, swaps;
  65. for (;;) {
  66. swaps = 0;
  67. for (i = 0; i + h < nmemb; i++) {
  68. if (compar(base + size * i, base + size * (i + h)) > 0) {
  69. swap(base + size * i, base + size * (i + h), size);
  70. swaps++;
  71. }
  72. }
  73. if (h == 1) {
  74. if (swaps == 0) break;
  75. } else {
  76. h = h * 10 / 13;
  77. }
  78. }
  79. }
  80. int main() {
  81. srand(time(NULL));
  82. size_t nel = 25000, width = sizeof (int);
  83. int *org = shuffle(_ia(0, nel - 1), nel);
  84. printf("qsort: %f\n", (double)check(qsort, org, nel, width, icmp) / CLOCKS_PER_SEC);
  85. printf("bsort: %f\n", (double)check(bubble_sort, org, nel, width, icmp) / CLOCKS_PER_SEC);
  86. printf("csort: %f\n", (double)check(comb_sort, org, nel, width, icmp) / CLOCKS_PER_SEC);
  87. return 0;
  88. }
Success #stdin #stdout 3.73s 2520KB
stdin
Standard input is empty
stdout
qsort: 0.000000
bsort: 3.740000
csort: 0.000000