Guest User

Untitled

a guest
Jul 19th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. package types
  2.  
  3. // Heap is a max heap
  4. type Heap struct {
  5. buf []int
  6. }
  7.  
  8. func (h *Heap) Peak() int {
  9. return h.buf[0]
  10. }
  11.  
  12. func (h *Heap) up(idx int) {
  13. if idx == 0 {
  14. return
  15. }
  16. parent := (idx - 1) / 2
  17. if h.buf[parent] < h.buf[idx] {
  18. h.buf[parent], h.buf[idx] = h.buf[idx], h.buf[parent]
  19. h.up(parent)
  20. return
  21. }
  22. }
  23.  
  24. func (h *Heap) Insert(key int) {
  25. h.buf = append(h.buf, key)
  26. h.up(len(h.buf) - 1)
  27. }
  28.  
  29. func (h *Heap) down(idx int) {
  30. leftChild := idx*2 + 1
  31. rightChild := idx*2 + 2
  32. if leftChild >= len(h.buf) {
  33. return
  34. }
  35.  
  36. swap := -1
  37. if h.buf[idx] < h.buf[leftChild] {
  38. if rightChild >= len(h.buf) || h.buf[leftChild] >= h.buf[rightChild] {
  39. swap = leftChild
  40. } else {
  41. swap = rightChild
  42. }
  43. } else if rightChild < len(h.buf) && h.buf[idx] < h.buf[rightChild] {
  44. swap = rightChild
  45. }
  46.  
  47. if swap < 0 {
  48. return
  49. }
  50.  
  51. h.buf[swap], h.buf[idx] = h.buf[idx], h.buf[swap]
  52. h.down(swap)
  53. }
  54.  
  55. func (h *Heap) Delete() int {
  56. max := h.buf[0]
  57. h.buf[0], h.buf[len(h.buf)-1] = h.buf[len(h.buf)-1], h.buf[0]
  58. h.buf = h.buf[:len(h.buf)-1]
  59. h.down(0)
  60. return max
  61. }
  62.  
  63. func (h *Heap) Build() {
  64. for i := len(h.buf) - 1; i >= 0; i -= 2 {
  65. h.down((i - 1) / 2)
  66. }
  67. }
  68.  
  69. // put the following to heap_test.go
  70. package types
  71.  
  72. import (
  73. "math/rand"
  74. "testing"
  75.  
  76. "github.com/stretchr/testify/assert"
  77. )
  78.  
  79. func TestHeap(t *testing.T) {
  80. const total = 101
  81. h := &Heap{}
  82. perm := rand.Perm(total)
  83. for _, v := range perm {
  84. h.Insert(v)
  85. }
  86. assert.Equal(t, total-1, h.Peak())
  87. for i := total - 1; i >= 0; i-- {
  88. assert.Equal(t, i, h.Delete())
  89. }
  90. }
  91.  
  92. func TestBuildHeap(t *testing.T) {
  93. const total = 101
  94. perm := rand.Perm(total)
  95. h := &Heap{buf: perm}
  96. h.Build()
  97. assert.Equal(t, total-1, h.Peak())
  98. for i := total - 1; i >= 0; i-- {
  99. assert.Equal(t, i, h.Delete())
  100. }
  101. }
  102.  
  103. func TestHeapSort(t *testing.T) {
  104. const total = 101
  105. perm := rand.Perm(total)
  106. h := &Heap{buf: perm}
  107. h.Build()
  108. assert.Equal(t, total-1, h.Peak())
  109. for i := total - 1; i >= 0; i-- {
  110. assert.Equal(t, i, h.Delete())
  111. }
  112. for i := 0; i < total; i++ {
  113. assert.Equal(t, i, perm[i])
  114. }
  115. }
Add Comment
Please, Sign In to add comment