From 955de2bdbf59ae2b6572a9e11d99a2e7a5516af9 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Tue, 26 Apr 2022 10:50:27 +0800 Subject: [PATCH] feat: add Dequeue function --- datastructure/queue/priorityqueue.go | 39 ++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/datastructure/queue/priorityqueue.go b/datastructure/queue/priorityqueue.go index deb4997..8ba8d2b 100644 --- a/datastructure/queue/priorityqueue.go +++ b/datastructure/queue/priorityqueue.go @@ -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]