0
0
DSA Javascriptprogramming~10 mins

Heap Extract Min or Max Bubble Down in DSA Javascript - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to get the left child index in a heap array.

DSA Javascript
function leftChildIndex(parentIndex) {
  return 2 * parentIndex [1] 1;
}
Drag options to blanks, or click blank then click option'
A+
B-
C/
D*
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction instead of addition
Using division or multiplication incorrectly
2fill in blank
medium

Complete the code to swap two elements in the heap array.

DSA Javascript
function swap(heap, i, j) {
  const temp = heap[i];
  heap[i] = heap[[1]];
  heap[j] = temp;
}
Drag options to blanks, or click blank then click option'
Aheap
Bi
Cj
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping with wrong indices
Using variable names incorrectly
3fill in blank
hard

Fix the error in the bubbleDown function to correctly compare and swap with the smaller child in a min-heap.

DSA Javascript
function bubbleDown(heap, index) {
  const left = 2 * index + 1;
  const right = 2 * index + 2;
  let smallest = index;

  if (left < heap.length && heap[left] [1] heap[smallest]) {
    smallest = left;
  }
  if (right < heap.length && heap[right] < heap[smallest]) {
    smallest = right;
  }
  if (smallest !== index) {
    swap(heap, index, smallest);
    bubbleDown(heap, smallest);
  }
}
Drag options to blanks, or click blank then click option'
A<
B>
C==
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using greater than instead of less than
Using equality instead of comparison
4fill in blank
hard

Fill both blanks to complete the extractMin function that removes the smallest element and restores the heap.

DSA Javascript
function extractMin(heap) {
  if (heap.length === 0) return null;
  const min = heap[0];
  heap[0] = heap[[1]];
  heap.[2]();
  bubbleDown(heap, 0);
  return min;
}
Drag options to blanks, or click blank then click option'
Aheap.length - 1
Bpop()
Cshift()
Dlength
Attempts:
3 left
💡 Hint
Common Mistakes
Using shift() which removes first element
Not removing last element after replacement
5fill in blank
hard

Fill all three blanks to complete the bubbleDown function for a max-heap that swaps with the larger child.

DSA Javascript
function bubbleDown(heap, index) {
  const left = 2 * index + 1;
  const right = 2 * index + 2;
  let largest = index;

  if (left < heap.length && heap[left] [1] heap[largest]) {
    largest = left;
  }
  if (right < heap.length && heap[right] [2] heap[largest]) {
    largest = right;
  }
  if (largest !== index) {
    swap(heap, index, largest);
    bubbleDown(heap, [3]);
  }
}
Drag options to blanks, or click blank then click option'
A>
B<
Clargest
Dindex
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong comparison operators
Recursing on wrong index