-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path20_heap_trace.go
More file actions
71 lines (60 loc) · 1.53 KB
/
20_heap_trace.go
File metadata and controls
71 lines (60 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Seriál "Programovací jazyk Go"
// https://www.root.cz/serialy/programovaci-jazyk-go/
//
// Dvacátá čtvrtá část
// Kontejnery v základní knihovně programovacího jazyka Go
// https://www.root.cz/clanky/kontejnery-v-zakladni-knihovne-programovaciho-jazyka-go/
//
// Repositář:
// https://github.com/tisnik/go-root/
//
// Seznam demonstračních příkladů z dvacáté čtvrté části:
// https://github.com/tisnik/go-root/blob/master/article_24/README.md
//
// Demonstrační příklad číslo 20:
// Úprava předchozího příkladu, aby zobrazoval prováděné operace
package main
import (
"container/heap"
"fmt"
)
// StringHeap represents simple heap abstract data structure based on array
type StringHeap []string
func (h StringHeap) Len() int {
return len(h)
}
func (h StringHeap) Less(i, j int) bool {
fmt.Printf("compare %s < %s\n", h[i], h[j])
return h[i] < h[j]
}
func (h StringHeap) Swap(i, j int) {
fmt.Printf("swap %s <-> %s\n", h[i], h[j])
h[i], h[j] = h[j], h[i]
}
func (h *StringHeap) Push(x interface{}) {
*h = append(*h, x.(string))
}
func (h *StringHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
func main() {
h := &StringHeap{}
heap.Init(h)
heap.Push(h, "a")
heap.Push(h, "z")
heap.Push(h, "c")
heap.Push(h, "b")
heap.Push(h, "d")
heap.Push(h, "x")
fmt.Println("\n-----------------------------")
fmt.Printf("First item: %s\n", (*h)[0])
i := 0
for h.Len() > 0 {
i++
fmt.Printf("item #%d = %s\n", i, heap.Pop(h))
}
}