heapsort.z80 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. heapsort:
  2. ;BC is the number of elements
  3. ;IX points to the compare/swap routine
  4. ld a,b
  5. or c
  6. ret z
  7. push bc
  8. call heapify
  9. pop bc
  10. _:
  11. dec bc
  12. push bc
  13. call heap_popswap
  14. pop bc
  15. ld a,b
  16. or c
  17. jr nz,-_
  18. ret
  19. heap_popswap:
  20. ld hl,0
  21. call heap_swap
  22. ld h,b
  23. ld l,c
  24. xor a
  25. ld b,a
  26. ld c,a
  27. heap_propogate:
  28. ;If (BC+1)*2 == number of elements, then need to do check_prop_special
  29. ;If (BC+1)*2 > number of elements, then we are done
  30. inc bc
  31. sbc hl,bc
  32. ret c
  33. sbc hl,bc
  34. ret c
  35. add hl,bc
  36. add hl,bc
  37. dec bc
  38. jr z,heap_check_prop_special
  39. push hl
  40. call heap_check_prop
  41. pop hl
  42. jr c,heap_propogate
  43. ret
  44. heap_check_prop:
  45. ;returns BC as the index of the largest child
  46. ;returns c flag set if still need to propogate
  47. ;First, compare BC's children
  48. push bc
  49. ld h,b
  50. ld l,c
  51. add hl,hl
  52. inc hl
  53. ld b,h
  54. ld c,l
  55. inc hl
  56. call heap_cmp
  57. ;nc means HL is the bigger child
  58. jr c,$+4
  59. ld b,h
  60. ld c,l
  61. pop hl
  62. push bc ;the child node that was bigger
  63. call heap_cmp
  64. ;nc means the parent is bigger than the children, good
  65. call c,heap_swap
  66. pop bc
  67. ret
  68. heap_check_prop_special:
  69. ;There are an even number of elements, so this parent has only one child.
  70. ;We'll do a special-case heap_check_prop
  71. ld h,b
  72. ld l,c
  73. add hl,hl
  74. inc hl
  75. call heap_cmp
  76. ;nc means the parent is bigger than the children, good
  77. jr c,heap_swap
  78. ret
  79. heap_swap:
  80. push bc
  81. push af
  82. scf
  83. call call_ix_01
  84. pop af
  85. pop bc
  86. ret
  87. heap_cmp:
  88. push hl
  89. push bc
  90. or a
  91. call call_ix_01
  92. pop bc
  93. pop hl
  94. ret
  95. heapify:
  96. ld h,b
  97. ld l,c
  98. srl b
  99. rr c
  100. jr heapify_start
  101. _:
  102. push hl
  103. push bc
  104. call heap_propogate
  105. pop bc
  106. pop hl
  107. heapify_start:
  108. ld a,b
  109. or c
  110. dec bc
  111. jr nz,-_
  112. ret