MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / MinPriorityQueue

Class MinPriorityQueue

Data-Structures/Heap/MinPriorityQueue.js:13–125  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

11// Functions: insert, delete, peek, isEmpty, print, heapSort, sink
12
13class MinPriorityQueue {
14 // calls the constructor and initializes the capacity
15 constructor(c) {
16 this.heap = []
17 this.capacity = c
18 this.size = 0
19 }
20
21 // inserts the key at the end and rearranges it
22 // so that the binary heap is in appropriate order
23 insert(key) {
24 if (this.isFull()) return
25 this.heap[this.size + 1] = key
26 let k = this.size + 1
27 while (k > 1) {
28 if (this.heap[k] < this.heap[Math.floor(k / 2)]) {
29 const temp = this.heap[k]
30 this.heap[k] = this.heap[Math.floor(k / 2)]
31 this.heap[Math.floor(k / 2)] = temp
32 }
33 k = Math.floor(k / 2)
34 }
35 this.size++
36 }
37
38 // returns the highest priority value
39 peek() {
40 return this.heap[1]
41 }
42
43 // returns boolean value whether the heap is empty or not
44 isEmpty() {
45 return this.size === 0
46 }
47
48 // returns boolean value whether the heap is full or not
49 isFull() {
50 return this.size === this.capacity
51 }
52
53 // prints the heap
54 print(output = (value) => console.log(value)) {
55 output(this.heap.slice(1))
56 }
57
58 // heap reverse can be done by performing swapping the first
59 // element with the last, removing the last element to
60 // new array and calling sink function.
61 heapReverse() {
62 const heapSort = []
63 while (this.size > 0) {
64 // swap first element with last element
65 ;[this.heap[1], this.heap[this.size]] = [
66 this.heap[this.size],
67 this.heap[1]
68 ]
69 heapSort.push(this.heap.pop())
70 this.size--

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected