Advertisement
AlienC4

assembly heap-sort

Mar 23rd, 2017
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. # Heap sort for the armlet
  2.  
  3. mov $1, >test_len
  4. loa $1, $1
  5. mov $0, >test_data
  6. sub $0, $0, 1 # index origin is 1
  7. mov $7, 1 # start heapifying at the origin
  8. @heapify:
  9. cmp $7, $1 # done with heapify?
  10. bab >getmax # ... yes
  11. mov $6, $7 # current index
  12. add $3, $0, $6 # address of current
  13. loa $2, $3 # load current value
  14. @upheap_loop:
  15. cmp $6, 1 # at heap top?
  16. bbe >heapify_next # ... yes
  17. lsr $3, $6, 1 # index of parent
  18. add $4, $0, $3 # address of parent
  19. loa $4, $4 # load parent
  20. cmp $4, $2 # compare parent and current
  21. bae >heapify_next # ... heap property holds
  22. add $5, $0, $6 # address of current
  23. sto $5, $4 # store parent to current
  24. mov $6, $3 # move to parent
  25. jmp >upheap_loop
  26. @heapify_next:
  27. add $3, $0, $6 # address of current
  28. sto $3, $2 # store current value here
  29. add $7, $7, 1
  30. jmp >heapify
  31. @getmax:
  32. cmp $1, 0 # done with max extraction?
  33. beq >sort_done # yes
  34. add $7, $0, 1 # address of heap top
  35. loa $3, $7 # load heap top
  36. add $2, $0, $1 # address of last element
  37. loa $6, $2 # load last element
  38. sto $2, $3 # heap top goes to last element
  39. sub $1, $1, 1 # decrease heap size
  40. mov $7, 1 # start downheap, $6 is current
  41. @downheap_loop:
  42. lsl $2, $7, 1 # left child index
  43. cmp $2, $1 # is there a left child?
  44. bab >downheap_done # ... no
  45. add $4, $2, $0 # left child address
  46. loa $4, $4 # load left child
  47. add $3, $2, 1 # right child index
  48. cmp $3, $1 # is there a right child?
  49. bab >downheap_left # ... no
  50. add $5, $3, $0 # right child address
  51. loa $5, $5 # load right child
  52. cmp $4, $5 # compare children
  53. bae >downheap_left # ... go left
  54. @downheap_right:
  55. cmp $6, $5 # compare current and right
  56. bae >downheap_done # ... ok to insert at current
  57. add $2, $0, $7 # current address
  58. sto $2, $5 # insert right to current
  59. mov $7, $3 # move to right
  60. jmp >downheap_loop
  61. @downheap_left:
  62. cmp $6, $4 # compare current and left
  63. bae >downheap_done # ... ok to insert at current
  64. add $3, $0, $7 # current address
  65. sto $3, $4 # insert left to current
  66. mov $7, $2 # move to left
  67. jmp >downheap_loop
  68. @downheap_done:
  69. add $2, $0, $7 # current address
  70. sto $2, $6 # store current here
  71. jmp >getmax
  72.  
  73. @sort_done:
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement