Skip to content

Commit fb92d84

Browse files
committed
add heap in javascript
1 parent 556c037 commit fb92d84

File tree

1 file changed

+139
-0
lines changed

1 file changed

+139
-0
lines changed

Heaps/heap.js

+139
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
/*
2+
Implement a Min-Heap class that supports
3+
4+
Building a Min Heap from an input array of integers.
5+
Inserting integers in the heap.
6+
Removing the heap's minimum / root value.
7+
Peeking at the heap's minimum / root value.
8+
Sifting integers up and down the heap, which is to be used when inserting and removing values.
9+
10+
Note that the heap should be represented in the form of an array.
11+
12+
Explanation:
13+
14+
The code snippet implements a MinHeap data structure in Go.
15+
16+
- `NewMinHeap`: This function creates a new MinHeap from an input array and returns a pointer to the MinHeap object.
17+
It calls the `BuildHeap` method to construct the heap structure.
18+
- `BuildHeap`: This method constructs the heap by iteratively calling `siftDown` on each parent node starting from the
19+
last non-leaf node.
20+
- `siftDown`: This method corrects the heap property by moving an element down the heap until it reaches its correct position. It compares the element with its children and swaps it with the smaller child if necessary.
21+
- `siftUp`: This method corrects the heap property by moving an element up the heap until it reaches its correct position.
22+
It compares the element with its parent and swaps it if necessary.
23+
- `Peek`: This method returns the minimum element in the heap (the root of the heap) without removing it.
24+
- `Remove`: This method removes and returns the minimum element in the heap. It swaps the root with the last element,
25+
removes the last element from the heap, and then calls `siftDown` to maintain the heap property.
26+
- `Insert`: This method inserts a new element into the heap. It appends the element to the end of the heap and then
27+
calls `siftUp` to maintain the heap property.
28+
- `swap`: This method swaps two elements in the heap given their indices.
29+
- `length`: This method returns the number of elements in the heap.
30+
31+
Overall, this code provides a basic implementation of a MinHeap data structure, allowing for efficient insertion, removal,
32+
and retrieval of the minimum element.
33+
34+
BuildHeap: O(n) time | O(1) space - where n is the length of the input array
35+
SiftDown: O(log(n)) time | O(1) space - where n is the length of the heap
36+
SiftUp: O(log(n)) time | O(1) space - where n is the length of the heap
37+
Peek: O(1) time | O(1) space
38+
Remove: O(log(n)) time | O(1) space - where n is the length of the heap
39+
Insert: O(log(n)) time | O(1) space - where n is the length of the heap
40+
41+
*/
42+
class MinHeap {
43+
constructor(array) {
44+
this.heap = array.slice(); // Create a copy of the input array
45+
this.size = array.length;
46+
this.buildHeap(); // Build the heap
47+
}
48+
49+
buildHeap() {
50+
const first = Math.floor((this.size - 2) / 2); // Start from the last parent node
51+
for (let currentIdx = first; currentIdx >= 0; currentIdx--) {
52+
this.siftDown(currentIdx);
53+
}
54+
}
55+
56+
siftDown(currentIndex) {
57+
let childOneIdx = currentIndex * 2 + 1; // Calculate the index of the first child
58+
while (childOneIdx < this.size) {
59+
let childTwoIdx = -1; // Initialize the index of the second child
60+
if (currentIndex * 2 + 2 < this.size) {
61+
childTwoIdx = currentIndex * 2 + 2; // Calculate the index of the second child if it exists
62+
}
63+
let indexToSwap = childOneIdx; // Assume the first child is the one to swap with
64+
if (childTwoIdx > -1 && this.heap[childOneIdx] > this.heap[childTwoIdx]) {
65+
// If the second child exists and is smaller, update the index to swap with
66+
indexToSwap = childTwoIdx;
67+
}
68+
if (this.heap[currentIndex] > this.heap[indexToSwap]) {
69+
// If the current element is greater than the one to swap with, perform the swap
70+
this.swap(currentIndex, indexToSwap);
71+
currentIndex = indexToSwap;
72+
childOneIdx = currentIndex * 2 + 1; // Update the index of the first child
73+
} else {
74+
return;
75+
}
76+
}
77+
}
78+
79+
siftUp() {
80+
let currentIdx = this.size - 1; // Start from the last element
81+
let parentIdx = Math.floor((currentIdx - 1) / 2); // Calculate the index of the parent
82+
while (currentIdx > 0) {
83+
const current = this.heap[currentIdx];
84+
const parent = this.heap[parentIdx];
85+
if (current < parent) {
86+
// If the current element is smaller than the parent, perform the swap
87+
this.swap(currentIdx, parentIdx);
88+
currentIdx = parentIdx;
89+
parentIdx = Math.floor((currentIdx - 1) / 2); // Update the index of the parent
90+
} else {
91+
return;
92+
}
93+
}
94+
}
95+
96+
peek() {
97+
if (this.size === 0) {
98+
return -1;
99+
}
100+
return this.heap[0]; // Return the minimum element at the top of the heap
101+
}
102+
103+
remove() {
104+
this.swap(0, this.size - 1); // Swap the root with the last element
105+
const peeked = this.heap[this.size - 1]; // Remove the last element (minimum) and store it
106+
this.size--;
107+
this.heap.length = this.size; // Resize the heap array
108+
this.siftDown(0); // Sift down the new root element
109+
return peeked;
110+
}
111+
112+
insert(value) {
113+
this.heap.push(value); // Append the new element to the end of the heap
114+
this.size++;
115+
this.siftUp(); // Sift up the new element to its correct position
116+
}
117+
118+
swap(i, j) {
119+
[this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]]; // Swap elements at indices i and j
120+
}
121+
122+
length() {
123+
return this.size; // Return the number of elements in the heap
124+
}
125+
}
126+
127+
// Example usage:
128+
const array = [9, 4, 7, 1, -2, 6, 5];
129+
const minHeap = new MinHeap(array);
130+
131+
console.log("Peek:", minHeap.peek());
132+
console.log("Remove:", minHeap.remove());
133+
console.log("Length:", minHeap.length());
134+
135+
minHeap.insert(2);
136+
minHeap.insert(-5);
137+
138+
console.log("Peek:", minHeap.peek());
139+
console.log("Length:", minHeap.length());

0 commit comments

Comments
 (0)