Skip to content

Commit

Permalink
Uses custom resize util instead of slice append
Browse files Browse the repository at this point in the history
  • Loading branch information
kc596 committed Nov 1, 2020
1 parent cc99598 commit 85bb492
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
25 changes: 20 additions & 5 deletions maxpq/pq.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@ type PQ struct {
// Returns a new max priority queue
func New() *PQ {
return &PQ{
n: 0,
nodes: make([]*Node, 0),
lock: sync.Mutex{},
n: 0,
lock: sync.Mutex{},
}
}

Expand All @@ -42,7 +41,11 @@ func (pq *PQ) Size() int {
func (pq *PQ) Insert(x *Node) {
pq.lock.Lock()
defer pq.lock.Unlock()
pq.nodes = append(pq.nodes, x)
// double the size of array if necessary
if pq.n >= len(pq.nodes) {
pq.resize(2 * (len(pq.nodes) + 1))
}
pq.nodes[pq.n] = x
pq.swim(pq.n)
pq.n += 1
}
Expand All @@ -65,10 +68,14 @@ func (pq *PQ) Pop() (*Node, error) {
return nil, errors.ErrNoSuchElement
}
max := pq.nodes[0]
pq.swap(0, pq.n-1)
pq.n -= 1
pq.swap(0, pq.n)
pq.nodes[pq.n] = nil
pq.sink(0)
// halve the size of array if necessary
if (pq.n > 0) && (pq.n == len(pq.nodes)/4) {
pq.resize(len(pq.nodes) / 2)
}
return max, nil
}

Expand Down Expand Up @@ -115,3 +122,11 @@ func (pq *PQ) swap(x, y int) {
pq.nodes[x] = pq.nodes[y]
pq.nodes[y] = temp
}

func (pq *PQ) resize(capacity int) {
temp := make([]*Node, capacity)
for i := 0; i < pq.n; i++ {
temp[i] = pq.nodes[i]
}
pq.nodes = temp
}
2 changes: 1 addition & 1 deletion maxpq/pq_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func TestPQNode(t *testing.T) {
assert.Equal(testPriority+9, node.GetPriority())

x := 1
funcValue := func() {x++}
funcValue := func() { x++ }
node = NewNode(funcValue, testPriority+10)
fn := node.GetFuncValue()
fn()
Expand Down

0 comments on commit 85bb492

Please sign in to comment.