Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6af937f

Browse files
feat(heap): remove by index
1 parent 1fa875f commit 6af937f

File tree

1 file changed

+10
-10
lines changed

1 file changed

+10
-10
lines changed

‎src/data-structures/heaps/heap.js

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,11 @@ class Heap {
3333
* Retrieves and removes the head of this heap, or returns null if this heap is empty.
3434
* @runtime O(log n)
3535
*/
36-
remove() {
36+
remove(index=0) {
3737
if (!this.size()) return null;
38-
this.swap(0, this.size() - 1);
39-
const value = this.array.pop();
40-
this.bubbleDown();
38+
this.swap(index, this.size() - 1);// swap with last
39+
const value = this.array.pop();// remove element
40+
this.bubbleDown(index);
4141
return value;
4242
}
4343

@@ -66,17 +66,17 @@ class Heap {
6666
* After removal, moves element downwards on the heap, if it's out of order
6767
* @runtime O(log n)
6868
*/
69-
bubbleDown() {
70-
let index = 0;
69+
bubbleDown(index=0) {
70+
let curr = index;
7171
const left = (i) => 2 * i + 1;
7272
const right = (i) => 2 * i + 2;
7373
const getTopChild = (i) => (right(i) < this.size()
7474
&& this.comparator(left(i), right(i)) > 0 ? right(i) : left(i));
7575

76-
while (left(index) < this.size() && this.comparator(index, getTopChild(index)) > 0) {
77-
const next = getTopChild(index);
78-
this.swap(index, next);
79-
index = next;
76+
while (left(curr) < this.size() && this.comparator(curr, getTopChild(curr)) > 0) {
77+
const next = getTopChild(curr);
78+
this.swap(curr, next);
79+
curr = next;
8080
}
8181
}
8282

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /