4.8 KiB
4.8 KiB
id | title | challengeType |
---|---|---|
587d825a367417b2b2512c8a | Insert an Element into a Max Heap | 1 |
Description
[ 6, 22, 30, 37, 63, 48, 42, 76 ]
The root node is the first element, 6. Its children are 22 and 30. If we look at the relationship between the array indices of these values, for index i the children are 2 * i + 1 and 2 * i + 2. Similarly, the element at index 0 is the parent of these two children at indices 1 and 2. More generally, we can find the parent of a node at any index with the following: Math.floor( (i - 1) / 2 ). These patterns will hold true as the binary tree grows to any size. Finally, we can make a slight adjustment to make this arithmetic even easier by skipping the first element in the array. Doing this creates the following relationship for any element at a given index i:
Example Array representation:
[ null, 6, 22, 30, 37, 63, 48, 42, 76 ]
An element's left child: i * 2
An element's right child: i * 2 + 1
An element's parent: Math.floor( i / 2 )
Once you wrap your head around the math, using an array representation is very useful because node locations can be quickly determined with this arithmetic and memory usage is diminished because you don't need to maintain references to child nodes.
Instructions
Tests
tests:
- text: The MaxHeap data structure exists.
testString: assert((function() { var test = false; if (typeof MaxHeap !== 'undefined') { test = new MaxHeap() }; return (typeof test == 'object')})());
- text: MaxHeap has a method called insert.
testString: assert((function() { var test = false; if (typeof MaxHeap !== 'undefined') { test = new MaxHeap() } else { return false; }; return (typeof test.insert == 'function')})());
- text: MaxHeap has a method called print.
testString: assert((function() { var test = false; if (typeof MaxHeap !== 'undefined') { test = new MaxHeap() } else { return false; }; return (typeof test.print == 'function')})());
- text: The insert method adds elements according to the max heap property.
testString: 'assert((function() { var test = false; if (typeof MaxHeap !== ''undefined'') { test = new MaxHeap() } else { return false; }; test.insert(50); test.insert(100); test.insert(700); test.insert(32); test.insert(51); let result = test.print(); return ((result.length == 5) ? result[0] == 700 : result[1] == 700) })());'
Challenge Seed
var MaxHeap = function() {
// change code below this line
// change code above this line
};
Solution
var MaxHeap = function() {
// change code below this line
this.heap = [undefined];
this.insert = (ele) => {
var index = this.heap.length;
var arr = [...this.heap];
arr.push(ele);
while (ele > arr[Math.floor(index / 2)]) {
arr[index] = arr[Math.floor(index / 2)];
arr[Math.floor(index / 2)] = ele;
index = arr[Math.floor(index / 2)];
}
this.heap = arr;
}
this.print = () => {
return this.heap
}
// change code above this line
};