fork download
  1. #include <stdio.h>
  2.  
  3. void myswap(int a[], int x, int y) {
  4. int tmp;
  5. tmp = a[x];
  6. a[x] = a[y];
  7. a[y] = tmp;
  8. }
  9.  
  10. void hsort(int a[], int n, int (*f)(int , int)) {
  11. int last, p, j, k;
  12. /* step.1 */
  13. last = 1;
  14. while (last < n) {
  15. p = last;
  16. while (p > 0) {
  17. j = (int)((p + 1) / 2) - 1;
  18. if (!f(a[p], a[j]))
  19. myswap(a, p, j);
  20. p = j;
  21. }
  22. last++;
  23. }
  24.  
  25. /* step.2 */
  26. last = n - 1;
  27. while (last > 0) {
  28. myswap(a, 0, last);
  29. p = 0;
  30. while (p < last) {
  31. j = 2 * p + 1;
  32. k = 2 * p + 2;
  33. if (j < last && k < last) {
  34. if (f(a[k], a[j])) {
  35. if (f(a[p], a[j])) {
  36. myswap(a, j, p);
  37. p = j;
  38. } else
  39. break;
  40. } else {
  41. if (f(a[p], a[k])) {
  42. myswap(a, k, p);
  43. p = k;
  44. } else
  45. break;
  46. }
  47. } else if (j < last && !(k < last)) {
  48. if (f(a[p], a[j])) {
  49. myswap(a, j, p);
  50. p = j;
  51. } else
  52. break;
  53. } else if (!(j < last) && k < last) {
  54. if (f(a[p], a[k])) {
  55. myswap(a, k, p);
  56. p = k;
  57. } else
  58. break;
  59. } else {
  60. /* non operation */
  61. break;
  62. }
  63. }
  64. last--;
  65. }
  66. }
  67.  
  68. int f(int x, int y) {
  69. if (x < y)
  70. return 1;
  71. else
  72. return 0;
  73. }
  74.  
  75. int main() {
  76. int i;
  77.  
  78. int a[] = {31, 41, 59, 26, 53, 58, 97, 93, 23, 84, 62};
  79. int n = (sizeof a) / (sizeof(int));
  80. hsort(a, n, f);
  81.  
  82. for (i = 0; i < n; i++)
  83. printf("%d,", a[i]);
  84. putchar('\n');
  85.  
  86. return 0;
  87. }
  88. /* end */
  89.  
Success #stdin #stdout 0s 2168KB
stdin
Standard input is empty
stdout
23,26,31,41,53,58,59,62,84,93,97,