mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2025-10-19 05:22:19 +00:00
good good study, day day up!
This commit is contained in:
50
vendor/gopl.io/ch4/treesort/sort.go
generated
vendored
Normal file
50
vendor/gopl.io/ch4/treesort/sort.go
generated
vendored
Normal file
@@ -0,0 +1,50 @@
|
||||
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
|
||||
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
|
||||
// See page 101.
|
||||
|
||||
// Package treesort provides insertion sort using an unbalanced binary tree.
|
||||
package treesort
|
||||
|
||||
//!+
|
||||
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
|
||||
}
|
||||
|
||||
//!-
|
23
vendor/gopl.io/ch4/treesort/sort_test.go
generated
vendored
Normal file
23
vendor/gopl.io/ch4/treesort/sort_test.go
generated
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
|
||||
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
|
||||
package treesort_test
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"sort"
|
||||
"testing"
|
||||
|
||||
"gopl.io/ch4/treesort"
|
||||
)
|
||||
|
||||
func TestSort(t *testing.T) {
|
||||
data := make([]int, 50)
|
||||
for i := range data {
|
||||
data[i] = rand.Int() % 50
|
||||
}
|
||||
treesort.Sort(data)
|
||||
if !sort.IntsAreSorted(data) {
|
||||
t.Errorf("not sorted: %v", data)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user