Guest User

Untitled

a guest
Jun 17th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. (def parent (i)
  2. (trunc (/ i 2)))
  3.  
  4. (def left (i)
  5. (* 2 i))
  6.  
  7. (def right (i)
  8. (+ 1 (* 2 i)))
  9.  
  10. (def elm (h i)
  11. (let ind (- i 1)
  12. h.ind))
  13.  
  14. (def setval (h i val)
  15. (= (h (- i 1)) val)
  16. h)
  17.  
  18. (def hswap (h i j)
  19. (= temp (elm h i))
  20. (setval h i (elm h j))
  21. (setval h j temp))
  22.  
  23. (def t-lgi (h idx (o curr))
  24. (if (empty idx)
  25. curr
  26. (t-lgi h (cdr idx) (if (no curr)
  27. (car idx)
  28. (> (elm h (car idx)) (elm h curr))
  29. (car idx)
  30. curr))))
  31.  
  32. (def largesti (h idx (o hsize (len h)))
  33. (t-lgi h (keep [>= hsize _] idx)))
  34.  
  35. (def max-heapify (h i (o hsize (len h)))
  36. (let largest
  37. (largesti h (list (left i) (right i) i) hsize)
  38. (when (~is i largest)
  39. (hswap h i largest)
  40. (max-heapify h largest hsize)))
  41. h)
  42.  
  43. (def build-max-heap (h (o hsize (len h)))
  44. (each x (rev:range 1 (trunc (/ hsize 2)))
  45. (max-heapify h x hsize))
  46. h)
  47.  
  48. (def heapsort (h)
  49. (hswap h 1 (len h))
  50. (each x (rev:range 2 (- (len h) 1))
  51. (max-heapify h 1 x)
  52. (hswap h 1 x))
  53. h)
  54.  
  55. ;test
  56. ;(max-heapify '(16 4 10 14 7 9 3 2 8 1) 2)
  57. ;(heapsort '(16 14 10 8 7 9 3 2 4 1))
Add Comment
Please, Sign In to add comment