feat: add Dequeue function

This commit is contained in:
dudaodong
2022-04-26 10:50:27 +08:00
parent a4c1d40faa
commit 955de2bdbf

View File

@@ -55,6 +55,25 @@ func (q *PriorityQueue[T]) Enqueue(val T) error {
return nil
}
// Dequeue delete and return max value in queue
func (q *PriorityQueue[T]) Dequeue() (T, bool) {
var val T
if q.IsEmpty() {
return val, false
}
max := q.items[1]
q.swap(1, q.size)
q.size--
q.sink(1)
//set zero value for rest values of the queue
q.items[q.size+1] = val
return max, true
}
// 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 {
@@ -63,6 +82,26 @@ func (q *PriorityQueue[T]) swim(index int) {
}
}
// sink when parent's key smaller than child's key, exchange parent's key with larger child's key.
func (q *PriorityQueue[T]) sink(index int) {
for 2*index <= q.size {
j := 2 * index
// get larger child node index
if j < q.size && q.comparator.Compare(j, j+1) < 0 {
j++
}
// if parent larger than child, stop
if !(q.comparator.Compare(index, j) < 0) {
break
}
q.swap(index, j)
index = j
}
}
// swap the two values at index i and j
func (q *PriorityQueue[T]) swap(i, j int) {
q.items[i], q.items[j] = q.items[j], q.items[i]