I am trying to write the function for creating a max heap in javascript My current code is
var arr = [5, 9, 6, 7, 1, 3, 8]
var heap = []
for (var i = 0; i < arr.length; i++) {
addtoheap(arr[i]);
}
function addtoheap(term) {
heap.push(term);
if (heap.length > 1) {
heapify(heap, (heap.length - 1))
}
console.log(heap);
}
function heapify(heap, i) {
if (i == 0) {
return;
}
if (heap[i] > heap[Math.floor(i / 2)]) {
var temp = heap[i];
console.log("Swapping" + heap[i] + "--" + heap[Math.floor(i / 2)]);
heap[i] = heap[Math.floor(i / 2)];
heap[Math.floor(i / 2)] = temp;
return heapify(heap, Math.floor(i / 2));
} else {
return;
}
}
And the output it gives is
[ 5 ]
Swapping9--5
[ 9, 5 ]
Swapping6--5
[ 9, 6, 5 ]
Swapping7--6
[ 9, 7, 5, 6 ]
[ 9, 7, 5, 6, 1 ]
[ 9, 7, 5, 6, 1, 3 ]
Swapping8--6
Swapping8--7
[ 9, 8, 5, 7, 1, 3, 6 ]
Not sure what I am doing wrong here ,can someone please point out the mistake in my logic ?
Expected output : a max heap [9,7,8,5,1,3,6]