From 9ed419e44a8cbcd29370de8dd6dcf1c01f0e05f7 Mon Sep 17 00:00:00 2001 From: andy_lien Date: Mon, 22 Apr 2024 18:15:04 +0800 Subject: [PATCH] feat: PQ - dequeue --- app-ch9-20.js | 45 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/app-ch9-20.js b/app-ch9-20.js index f8236a4..9692fee 100644 --- a/app-ch9-20.js +++ b/app-ch9-20.js @@ -33,11 +33,54 @@ class PriorityQueue { parentIndex = Math.floor((newIndex - 1) / 2); } } + + dequeue(){ + if (this.values.length === 0) return null; + if (this.values.length === 1) { + const removedNode = this.values.pop(); + return removedNode; + } + + [this.values[0], this.values[this.values.length - 1]] = [this.values[this.values.length - 1], this.values[0]]; + + const removedNode = this.values.pop(); + this.maxHeapify(0) + + return removedNode; + } + + maxHeapify(i) { + let largestIndex = undefined; + let left = i * 2 + 1; + let right = i * 2 + 2; + const length = this.values.length; + + left <= length - 1 && this.values[left].priority > this.values[i].priority + ? largestIndex = left + : largestIndex = i; + + if (right <= length - 1 && this.values[right].priority > this.values[largestIndex].priority) { + largestIndex = right; + } + + if (largestIndex !== i) { + [this.values[i], this.values[largestIndex]] = [this.values[largestIndex], this.values[i]]; + this.maxHeapify(largestIndex); + } + } } const pq1 = new PriorityQueue(); pq1.enqueue('Eat breakfast', 5); pq1.enqueue('Learn Java', 2); pq1.enqueue('Learn JavaScript', 7); +pq1.enqueue('Buy Textbooks', 8); +pq1.enqueue('Watch Netflix', 12); +pq1.enqueue('Pay Bills', 15); + +console.log(pq1) -console.log(pq1) \ No newline at end of file +while(pq1.values.length >= 1){ + const { value, priority } = pq1.dequeue(); + console.log(value + ' - Priority: ' + priority); +} \ No newline at end of file