Skip to content

Commit 58194df

Browse files
author
hero
committed
添加堆排序
1 parent 9f5db5a commit 58194df

File tree

3 files changed

+92
-0
lines changed

3 files changed

+92
-0
lines changed

README.md

+4
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@
99
1010
### leet_code [leet_code刷题]
1111
1: leet_code刷题
12+
13+
### heap []
14+
1: max_heap_test 大顶推
15+
2: min_heap_test 小顶堆
1216

1317
### linked_list [链表]
1418
1: cycle_list 循环链表

heap/max_heap_test.go

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package heap
2+
3+
import (
4+
"container/heap"
5+
"fmt"
6+
"testing"
7+
)
8+
9+
type MaxHeap []int
10+
11+
func (m MaxHeap) Len() int {
12+
return len(m)
13+
}
14+
15+
func (m MaxHeap) Less(i, j int) bool {
16+
return m[i] > m[j]
17+
}
18+
19+
func (m MaxHeap) Swap(i, j int) {
20+
m[i], m[j] = m[j], m[i]
21+
}
22+
23+
func (m *MaxHeap) Push(x interface{}) {
24+
*m = append(*m, x.(int))
25+
}
26+
27+
func (m *MaxHeap) Pop() interface{} {
28+
old := *m
29+
n := len(old)
30+
x := old[n-1]
31+
*m = old[0 : n-1]
32+
return x
33+
}
34+
35+
func TestMaxHeap(t *testing.T) {
36+
m := &MaxHeap{
37+
2, 10, 5, 9, 12, 7, 3,
38+
}
39+
heap.Init(m)
40+
for m.Len() > 0 {
41+
fmt.Printf("%d ", heap.Pop(m))
42+
}
43+
44+
}

heap/min_heap_test.go

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package heap
2+
3+
import (
4+
"container/heap"
5+
"fmt"
6+
"testing"
7+
)
8+
9+
type MinHeap []int
10+
11+
func (m MinHeap) Len() int {
12+
return len(m)
13+
}
14+
15+
func (m MinHeap) Less(i, j int) bool {
16+
return m[i] < m[j]
17+
}
18+
19+
func (m MinHeap) Swap(i, j int) {
20+
m[i], m[j] = m[j], m[i]
21+
}
22+
23+
func (m *MinHeap) Push(x interface{}) {
24+
*m = append(*m, x.(int))
25+
}
26+
27+
func (m *MinHeap) Pop() interface{} {
28+
old := *m
29+
n := len(old)
30+
x := old[n-1]
31+
*m = old[0 : n-1]
32+
return x
33+
}
34+
35+
func TestMinHeap(t *testing.T) {
36+
m := &MinHeap{
37+
2, 10, 5, 9, 12, 7, 3,
38+
}
39+
heap.Init(m)
40+
for m.Len() > 0 {
41+
fmt.Printf("%d ", heap.Pop(m))
42+
}
43+
44+
}

0 commit comments

Comments
 (0)