Complete the code to create a min heap by using the correct comparison operator.
function compare(a, b) { return a [1] b; } // For min heapFor a min heap, the comparison should return true when a is less than b, so the smallest element rises to the top.
Complete the code to create a max heap by using the correct comparison operator.
function compare(a, b) { return a [1] b; } // For max heapFor a max heap, the comparison should return true when a is greater than b, so the largest element rises to the top.
Fix the error in the code that builds a min heap by choosing the correct comparison operator.
function buildHeap(arr) { return arr.sort((a, b) => a [1] b ? -1 : 1); } // Min heapSorting with a < b ensures the smallest elements come first, which is needed for a min heap.
Fill both blanks to complete the function that decides which heap to use based on the need for smallest or largest element retrieval.
function chooseHeap(type) {
if (type === 'min') return [1];
else if (type === 'max') return [2];
else return null;
}Return MinHeap when the smallest element is needed, and MaxHeap when the largest element is needed.
Fill all three blanks to complete the code that inserts a new element into a heap and maintains the heap property.
function insert(heap, element) {
heap.push(element);
let index = heap.length - 1;
while (index > 0) {
let parent = Math.floor((index - 1) / 2);
if (heap[parent] [1] heap[index]) break;
[heap[parent], heap[index]] = [heap[index], heap[parent]];
index = parent;
}
return heap;
}For a max heap insertion, swap if parent is less than child (parent < child), so the largest element stays on top.