mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-14 01:32:27 +08:00
test: add unit test for PriorityQueue Dequeue function
This commit is contained in:
@@ -76,7 +76,7 @@ func (q *PriorityQueue[T]) Dequeue() (T, bool) {
|
|||||||
|
|
||||||
// swim when child's key is larger than parent's key, exchange them.
|
// swim when child's key is larger than parent's key, exchange them.
|
||||||
func (q *PriorityQueue[T]) swim(index int) {
|
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)
|
q.swap(index, index/2)
|
||||||
index = index / 2
|
index = index / 2
|
||||||
}
|
}
|
||||||
@@ -89,11 +89,11 @@ func (q *PriorityQueue[T]) sink(index int) {
|
|||||||
j := 2 * index
|
j := 2 * index
|
||||||
|
|
||||||
// get larger child node 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++
|
j++
|
||||||
}
|
}
|
||||||
// if parent larger than child, stop
|
// 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
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -37,5 +37,24 @@ func TestPriorityQueue_Enqueue(t *testing.T) {
|
|||||||
queueData := pq.Data()
|
queueData := pq.Data()
|
||||||
assert.Equal([]int{10, 9, 6, 7, 8, 2, 5, 1, 4, 3}, queueData)
|
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())
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user