forked from OPCODE-Open-Spring-Fest/Algo-Visualizer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap.js
More file actions
63 lines (55 loc) · 1.34 KB
/
heap.js
File metadata and controls
63 lines (55 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
export function createHeap(type = "max") {
let heap = [];
const compare = (a, b) => (type === "max" ? a > b : a < b);
const swap = (i, j) => {
[heap[i], heap[j]] = [heap[j], heap[i]];
};
const heapifyUp = () => {
let i = heap.length - 1;
while (i > 0) {
let p = Math.floor((i - 1) / 2);
if (compare(heap[i], heap[p])) {
swap(i, p);
i = p;
} else break;
}
};
const heapifyDown = () => {
let i = 0;
const n = heap.length;
while (true) {
let l = 2 * i + 1,
r = 2 * i + 2,
target = i; // ✅ changed from 'largest' → 'target' for clarity
if (l < n && compare(heap[l], heap[target])) target = l;
if (r < n && compare(heap[r], heap[target])) target = r;
if (target === i) break;
swap(i, target);
i = target;
}
};
return {
getHeap: () => [...heap],
insert: (val) => {
heap.push(val);
heapifyUp();
return [...heap];
},
deleteRoot: () => {
if (heap.length === 0) return [];
if (heap.length === 1) {
heap.pop();
return [];
}
// ✅ fixed: replace root with last, pop last, then heapify
heap[0] = heap[heap.length - 1];
heap.pop();
heapifyDown();
return [...heap];
},
reset: () => {
heap = [];
return [];
},
};
}