Skip to content

Commit

Permalink
Merge pull request wangzheng0822#175 from LYDongD/master
Browse files Browse the repository at this point in the history
add heap algo in golang
  • Loading branch information
wangzheng0822 authored Dec 3, 2018
2 parents 9f6df6f + 086276d commit 66a90de
Show file tree
Hide file tree
Showing 2 changed files with 137 additions and 0 deletions.
83 changes: 83 additions & 0 deletions go/28_heap/heap.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package heap

type Heap struct {
a []int
n int
count int
}

//init heap
func NewHeap(capacity int) *Heap {
heap := &Heap{}
heap.n = capacity
heap.a = make([]int, capacity+1)
heap.count = 0
return heap
}

//top-max heap -> heapify from down to up
func (heap *Heap) insert(data int) {
//defensive
if heap.count == heap.n {
return
}

heap.count++
heap.a[heap.count] = data

//compare with parent node
i := heap.count
parent := i / 2
for parent > 0 && heap.a[parent] < heap.a[i] {
swap(heap.a, parent, i)
i = parent
parent = i / 2
}
}

//heapfify from up to down
func (heap *Heap) removeMax() {

//defensive
if heap.count == 0 {
return
}

//swap max and last
swap(heap.a, 1, heap.count)
heap.count--

//heapify from up to down
heapifyUpToDown(heap.a, heap.count)
}

//heapify
func heapifyUpToDown(a []int, count int) {

for i := 1; i <= count/2; {

maxIndex := i
if a[i] < a[i*2] {
maxIndex = i * 2
}

if i*2+1 <= count && a[maxIndex] < a[i*2+1] {
maxIndex = i*2 + 1
}

if maxIndex == i {
break
}

swap(a, i, maxIndex)
i = maxIndex
}

}

//swap two elements
func swap(a []int, i int, j int) {
tmp := a[i]
a[i] = a[j]
a[j] = tmp
}
54 changes: 54 additions & 0 deletions go/28_heap/heap_sort.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package heap

//build a heap
func buidHeap(a []int, n int) {

//heapify from the last parent node
for i := n / 2; i >= 1; i-- {
heapifyUpToDown(a, i, n)
}

}

//sort by ascend, a index begin from 1, has n elements
func sort(a []int, n int) {
buidHeap(a, n)

k := n
for k >= 1 {
swap(a, 1, k)
heapifyUpToDown(a, 1, k-1)
k--
}
}

//heapify from up to down , node index = top
func heapifyUpToDown(a []int, top int, count int) {

for i := top; i <= count/2; {

maxIndex := i
if a[i] < a[i*2] {
maxIndex = i * 2
}

if i*2+1 <= count && a[maxIndex] < a[i*2+1] {
maxIndex = i*2 + 1
}

if maxIndex == i {
break
}

swap(a, i, maxIndex)
i = maxIndex
}

}

//swap two elements
func swap(a []int, i int, j int) {
tmp := a[i]
a[i] = a[j]
a[j] = tmp
}

0 comments on commit 66a90de

Please sign in to comment.