So I've been trying to implement the Max Heap. The use I want to give to it is that, at any one time, I want the first 3 elements of the heap (that is, the root and its two children) to always be the highest in the whole heap.
I thought the heap property would guarantee this, but not a single implementation example I have come across has been able to solve the fact that sometimes, there are elements in one level of the heap that are lower than an element in a higher level. This is the implementation I've been using, basically by using examples I have found on the internet as reference:
let createHeap = function(){
return {
arr:[],
size: 0,
getParent: function(i) { return Math.floor((i-1)/2) },
getLeft: function(i) { return (2*i + 1) },
getRight: function(i) { return (2*i + 2) },
insert: function(val){
let i = this.size
this.size++
this.arr[i] = val;
if(i!=0){
for(let j = this.getParent(i);j>=0;j--){
this.heapify(j)
}
}
},
heapify: function(i){
let largest = i;
let leftIndex = this.getLeft(i)
let rightIndex = this.getRight(i)
if (leftIndex < this.size && this.arr[leftIndex] > this.arr[largest])
largest = leftIndex
if (rightIndex < this.size && this.arr[rightIndex] > this.arr[largest])
largest = rightIndex;
if (largest != i) {
let temp = this.arr[largest];
this.arr[largest] = this.arr[i]
this.arr[i] = temp
this.heapify(largest);
}
}
}
}
Now, the problem is, when I insert the following values in this order: 1, 2, 3, 4, 5
The result I get for the heap is:
5
|\
4 2
|\
1 3
This is clear when you read what the code does, but doesn't seem to conserve heap property as far as I got to understand what heap property means. The code is missing something to get to do what I want it to do, but I don't want to implement changes that would increase the complexity too badly, so I wanted to ask: