Inserting in min-heap?

  someone please explain what's happening inside the while loop?


   this.insert = function(num) {
	heap.push(num);
	if (heap.length > 2) {
		let idx = heap.length - 1;
		while (heap[idx] < heap[Math.floor(idx/2)]) {
			if (idx >= 1) {
				[heap[Math.floor(idx/2)], heap[idx]] = [heap[idx], heap[Math.floor(idx/2)]];
				if (Math.floor(idx/2) > 1) {
					idx = Math.floor(idx/2);
				} else {
					break;
				};
			};
		};
	};
};

The number to insert is put into the correct place inside the heap’s data store.

sorry i need step by step instruction

Here’s an explanation what binary heaps are: https://eloquentjavascript.net/1st_edition/appendix2.html

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.