forked from torbiak/gopl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsort.go
64 lines (57 loc) · 1.19 KB
/
sort.go
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
// ex7.3 provides insertion sort using an unbalanced binary tree, and a String
// method to visualize the tree.
package treesort
import (
"bytes"
"fmt"
)
type tree struct {
value int
left, right *tree
}
// Sort sorts values in place.
func Sort(values []int) {
var root *tree
for _, v := range values {
root = add(root, v)
}
appendValues(values[:0], root)
}
// appendValues appends the elements of t to values in order
// and returns the resulting slice.
func appendValues(values []int, t *tree) []int {
if t != nil {
values = appendValues(values, t.left)
values = append(values, t.value)
values = appendValues(values, t.right)
}
return values
}
func add(t *tree, value int) *tree {
if t == nil {
// Equivalent to return &tree{value: value}.
t = new(tree)
t.value = value
return t
}
if value < t.value {
t.left = add(t.left, value)
} else {
t.right = add(t.right, value)
}
return t
}
func (t *tree) String() string {
order := make([]int, 0)
order = appendValues(order, t)
if len(order) == 0 {
return "[]"
}
b := &bytes.Buffer{}
fmt.Fprintf(b, "[%d", order[0])
for _, v := range order[1:] {
fmt.Fprintf(b, " %d", v)
}
fmt.Fprintf(b, "]")
return b.String()
}