1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

test: add unit test for PriorityQueue Dequeue function

This commit is contained in:
dudaodong
2022-04-26 10:56:24 +08:00
parent 955de2bdbf
commit 652916b7d7
2 changed files with 23 additions and 4 deletions

View File

@@ -76,7 +76,7 @@ func (q *PriorityQueue[T]) Dequeue() (T, bool) {
// swim when child's key is larger than parent's key, exchange them.
func (q *PriorityQueue[T]) swim(index int) {
for index > 1 && q.comparator.Compare(index/2, index) < 0 {
for index > 1 && q.comparator.Compare(q.items[index/2], q.items[index]) < 0 {
q.swap(index, index/2)
index = index / 2
}
@@ -89,11 +89,11 @@ func (q *PriorityQueue[T]) sink(index int) {
j := 2 * index
// get larger child node index
if j < q.size && q.comparator.Compare(j, j+1) < 0 {
if j < q.size && q.comparator.Compare(q.items[j], q.items[j+1]) < 0 {
j++
}
// if parent larger than child, stop
if !(q.comparator.Compare(index, j) < 0) {
if !(q.comparator.Compare(q.items[index], q.items[j]) < 0) {
break
}

View File

@@ -37,5 +37,24 @@ func TestPriorityQueue_Enqueue(t *testing.T) {
queueData := pq.Data()
assert.Equal([]int{10, 9, 6, 7, 8, 2, 5, 1, 4, 3}, queueData)
// assert.IsNotNil(err)
}
func TestPriorityQueue_Dequeue(t *testing.T) {
assert := internal.NewAssert(t, "TestPriorityQueue_Dequeue")
comparator := &intComparator{}
pq := NewPriorityQueue[int](10, comparator)
_, ok := pq.Dequeue()
assert.Equal(false, ok)
for i := 1; i < 11; i++ {
pq.Enqueue(i)
}
val, ok := pq.Dequeue()
assert.Equal(true, ok)
assert.Equal(10, val)
assert.Equal([]int{9, 8, 6, 7, 3, 2, 5, 1, 4}, pq.Data())
}