fix max heap insert function (#43285)

pull/43327/head
Anshul Singh 2021-08-27 20:40:29 +05:30 committed by GitHub
parent e67870f243
commit f834d648e8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 24 deletions

View File

@ -133,20 +133,28 @@ var MaxHeap = function() {
```js
var MaxHeap = function() {
// Only change code below this line
this.heap = [null];
this.insert = (ele) => {
var index = this.heap.length;
var arr = [...this.heap];
arr.push(ele);
while (ele > arr[Math.floor(index / 2)] && index > 1) {
arr[index] = arr[Math.floor(index / 2)];
arr[Math.floor(index / 2)] = ele;
index = arr[Math.floor(index / 2)];
}
this.heap = arr;
this.heap = [];
this.parent = index => {
return Math.floor((index - 1) / 2);
}
this.insert = element => {
this.heap.push(element);
this.heapifyUp(this.heap.length - 1);
}
this.heapifyUp = index => {
let currentIndex = index,
parentIndex = this.parent(currentIndex);
while (currentIndex > 0 && this.heap[currentIndex] > this.heap[parentIndex]) {
this.swap(currentIndex, parentIndex);
currentIndex = parentIndex;
parentIndex = this.parent(parentIndex);
}
}
this.swap = (index1, index2) => {
[this.heap[index1], this.heap[index2]] = [this.heap[index2], this.heap[index1]];
}
this.print = () => {
return this.heap.slice(1);
return this.heap;
}
// Only change code above this line
};

View File

@ -114,21 +114,29 @@ assert(
## --seed-contents--
```js
var MaxHeap = function() {
this.heap = [null];
this.insert = (ele) => {
var index = this.heap.length;
var arr = [...this.heap];
arr.push(ele);
while (ele > arr[Math.floor(index / 2)] && index > 1) {
arr[index] = arr[Math.floor(index / 2)];
arr[Math.floor(index / 2)] = ele;
index = arr[Math.floor(index / 2)];
var MaxHeap = function () {
this.heap = [];
this.parent = index => {
return Math.floor((index - 1) / 2);
}
this.insert = element => {
this.heap.push(element);
this.heapifyUp(this.heap.length - 1);
}
this.heapifyUp = index => {
let currentIndex = index,
parentIndex = this.parent(currentIndex);
while (currentIndex > 0 && this.heap[currentIndex] > this.heap[parentIndex]) {
this.swap(currentIndex, parentIndex);
currentIndex = parentIndex;
parentIndex = this.parent(parentIndex);
}
this.heap = arr;
}
this.swap = (index1, index2) => {
[this.heap[index1], this.heap[index2]] = [this.heap[index2], this.heap[index1]];
}
this.print = () => {
return this.heap.slice(1);
return this.heap;
}
// Only change code below this line