Skip to content

Commit

Permalink
change heap, add rise and sink, use recursion
Browse files Browse the repository at this point in the history
  • Loading branch information
Yu Zhao committed May 25, 2018
1 parent 9fc9e2f commit 9ed559d
Showing 1 changed file with 68 additions and 37 deletions.
105 changes: 68 additions & 37 deletions ch11/heap.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ func main() {
arr := []int{1,2,3,4,5,6,7,8}
heapMax := NewHeap(arr, false)
fmt.Println(heapMax)
heapMax.Insert(9)
fmt.Println(heapMax)
heapMax.DeleteRoot()
fmt.Println(heapMax)
// heapMax := NewHeap(arr, true)
// fmt.Println(heapMax)
arr1 := []int{1,2,3,4,5,6,7}
Expand Down Expand Up @@ -104,41 +108,67 @@ func NewHeap(arr []int, isMin bool) *Heap {

// sink forward
for i := center; i >= 0 ; i -- {
tmp := 2 * i + 1
tmp1 := tmp + 1

if tmp1 < size && heap.compare(tmp, tmp1) {
tmp = tmp1
}

if heap.compare(i, tmp) {
heap.swap(i, tmp)
if tmp1 <= center {
i = tmp1
}
}
heap.sink(i)
}
return heap
}

// use recursion
func (h *Heap) sink(i int) {
tmp := 2 * i + 1
tmp1 := tmp + 1

if tmp1 < h.size && h.compare(tmp, tmp1) {
tmp = tmp1
}

// if h.compare(i, tmp) {
// h.swap(i, tmp)
// if tmp <= center {
// i = tmp + 1 // here tmp + 1, think why!!!???
// // the 3rd for clause will do i--
// // so tmp + 1 will let i = tmp when
// // next loop start
// }
// }

if tmp < h.size && h.compare(i, tmp) {
h.swap(i, tmp)
h.sink(tmp)
}
}

func (h *Heap) rise(low int) {
high := (low - 1) / 2
for low > 0 && h.compare(high, low) {
h.swap(low, high)
low = high
high = (low - 1) / 2
}
}

func (h *Heap) Insert(i int) {
h.size ++
h.arr = append(h.arr, i)

low := h.size - 1
high := low / 2
// low := h.size - 1
// high := (low - 1) / 2
// rise
for low != 0 && h.compare(high, low) {
h.swap(low, high)
low = high
high = low / 2
}
h.rise(h.size - 1)
}

func (h *Heap) IsEmpty() bool {
return h.size == 0
}

// this will be getMax when isMax
// and getMin when isMin
func (h *Heap) GetRoot() {
return h.arr[0]
func (h *Heap) Peek() (int, bool) {
if h.IsEmpty() {
fmt.Println("heap is empty.")
return 0, false
}
return h.arr[0], true
}

func (h *Heap) DeleteRoot() {
Expand All @@ -154,19 +184,20 @@ func (h *Heap) DeleteRoot() {
h.size --

// sink one
for i:= 0 ; i < maxIndex; {
tmp := 2 * i + 1
tmp1 := tmp + 1

if tmp1 < maxIndex && h.compare(tmp, tmp1) {
tmp = tmp1
}

if tmp < maxIndex && h.compare(i, tmp) {
h.swap(i, tmp)
i = tmp
} else {
break;
}
}
// for i:= 0 ; i < maxIndex; {
// tmp := 2 * i + 1
// tmp1 := tmp + 1

// if tmp1 < maxIndex && h.compare(tmp, tmp1) {
// tmp = tmp1
// }

// if tmp < maxIndex && h.compare(i, tmp) {
// h.swap(i, tmp)
// i = tmp
// } else {
// break;
// }
// }
h.sink(0)
}

0 comments on commit 9ed559d

Please sign in to comment.