0

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]

Tanmay Bhattacharya
  • 551
  • 1
  • 5
  • 16

1 Answers1

0

As mentioned by Prasun in the comments , JS uses indexes from 0 ,and the algorithm uses indexes starting from 1. The following fix makes it work

function heapify(heap,i){
  if(i==0) return;
  if(heap[i] > heap[Math.floor((i-1)/2)]) { 
    var temp = heap[i];
    console.log("Swapping" +heap[i] +"--" + heap[Math.floor(i/2)]);
    heap[i] = heap[Math.floor((i-1)/2)];
    heap[Math.floor((i-1)/2)] = temp;
    return heapify(heap,Math.floor((i-1)/2));
  }
  else return;
}
Omkar Kulkarni
  • 1,091
  • 10
  • 22
Tanmay Bhattacharya
  • 551
  • 1
  • 5
  • 16
  • 1
    Please, stop repeating yourself. Make a variable: `var parent = Math.floor((i-1)/2);`, and then use that in place of the expression. It makes your code a whole lot easier to read, and to modify. Plus, if you discover that you want to change the expression later, you only need to change it in one place. – Jim Mischel Aug 28 '19 at 18:53