mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-06 09:28:26 +08:00
This commit is contained in:

committed by
GitHub

parent
32781c2aa1
commit
4fb0809666
@ -57,13 +57,22 @@ class MinPriorityQueue {
|
||||
output(this.heap.slice(1))
|
||||
}
|
||||
|
||||
// heap sorting can be done by performing
|
||||
// delete function to the number of times of the size of the heap
|
||||
// it returns reverse sort because it is a min priority queue
|
||||
heapSort () {
|
||||
for (let i = 1; i < this.capacity; i++) {
|
||||
this.delete()
|
||||
// heap reverse can be done by performing swaping the first
|
||||
// element with the last, removing the last element to
|
||||
// new array and calling sink function.
|
||||
heapReverse () {
|
||||
const heapSort = []
|
||||
while (this.size > 0) {
|
||||
// swap first element with last element
|
||||
[this.heap[1], this.heap[this.size]] = [this.heap[this.size], this.heap[1]]
|
||||
heapSort.push(this.heap.pop())
|
||||
this.size--
|
||||
this.sink()
|
||||
}
|
||||
// first value from heap it's empty to respect
|
||||
// structure with 1 as index of the first element
|
||||
this.heap = [undefined, ...heapSort.reverse()]
|
||||
this.size = heapSort.length
|
||||
}
|
||||
|
||||
// this function reorders the heap after every delete function
|
||||
@ -98,11 +107,17 @@ class MinPriorityQueue {
|
||||
}
|
||||
}
|
||||
|
||||
// deletes the highest priority value from the heap
|
||||
// deletes the highest priority value from the heap. The last
|
||||
// element goes to ahead to first position and reorder heap
|
||||
delete () {
|
||||
// checks empty and one element array conditions
|
||||
if (this.isEmpty()) return
|
||||
if (this.size === 1) {
|
||||
this.size--
|
||||
return this.heap.pop()
|
||||
}
|
||||
const min = this.heap[1]
|
||||
this.heap[1] = this.heap[this.size]
|
||||
this.heap[this.size] = min
|
||||
this.heap[1] = this.heap.pop()
|
||||
this.size--
|
||||
this.sink()
|
||||
return min
|
||||
|
Reference in New Issue
Block a user