-
Notifications
You must be signed in to change notification settings - Fork 23
/
binary_search_st.go
105 lines (86 loc) · 1.98 KB
/
binary_search_st.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package algs4
const initCapacity = 2
// BinarySearchST is symbol table
type BinarySearchST struct {
keys []Key // defined in st.go
vals []interface{}
n int
}
// NewBinarySearchST returns an bst with init capcity
func NewBinarySearchST() *BinarySearchST {
return &BinarySearchST{
keys: make([]Key, initCapacity),
vals: make([]interface{}, initCapacity),
}
}
func (st *BinarySearchST) resize(capacity int) {
newKeys := make([]Key, capacity)
copy(newKeys, st.keys)
st.keys = newKeys
newVals := make([]interface{}, capacity)
copy(newVals, st.vals)
st.vals = newVals
}
func (st BinarySearchST) rank(key Key) int {
lo, hi := 0, st.n-1
for lo <= hi {
mid := lo + (hi-lo)/2
cmp := key.compareTo(st.keys[mid])
if cmp < 0 {
hi = mid - 1
} else if cmp > 0 {
lo = mid + 1
} else {
return mid
}
}
return lo
}
// Put add new key value pair into the st
func (st *BinarySearchST) Put(key Key, val interface{}) {
i := st.rank(key)
if i < st.n && st.keys[i] == key {
st.vals[i] = val
return
}
if st.n == len(st.keys) {
st.resize(2 * len(st.keys))
}
for j := st.n; j > i; j-- {
st.keys[j], st.vals[j] = st.keys[j-1], st.vals[j-1]
}
st.keys[i], st.vals[i] = key, val
st.n++
}
// Get add new key value pair into the st
func (st *BinarySearchST) Get(key Key) interface{} {
i := st.rank(key)
if i < st.n && key.compareTo(st.keys[i]) == 0 {
return st.vals[i]
}
return nil
}
// GetInt return the val as int( have to do this since GO doesn't have generics)
func (st *BinarySearchST) GetInt(key Key) int {
return st.Get(key).(int)
}
// Delete ...
func (st *BinarySearchST) Delete(key Key) {
st.Put(key, nil)
}
// Contains ...
func (st *BinarySearchST) Contains(key Key) bool {
return st.Get(key) != nil
}
// Size ...
func (st *BinarySearchST) Size() int {
return st.n
}
// IsEmpty add new key value pair into the st
func (st BinarySearchST) IsEmpty() bool {
return st.Size() == 0
}
// Keys ...
func (st *BinarySearchST) Keys() []Key {
return st.keys[:st.n]
}