0
0
DSA Javascriptprogramming~10 mins

Build Heap from Array Heapify 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 index of the left child 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 multiplication or division incorrectly.
2fill in blank
medium

Complete the code to swap two elements in the array.

DSA Javascript
function swap(arr, i, j) {
  const temp = arr[i];
  arr[i] = arr[[1]];
  arr[[1]] = temp;
}
Drag options to blanks, or click blank then click option'
Aarr
Bi
Cj
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same index for both assignments.
Using an invalid variable.
3fill in blank
hard

Fix the error in the heapify function to correctly compare and swap with the largest child.

DSA Javascript
function heapify(arr, n, i) {
  let largest = i;
  const left = 2 * i + 1;
  const right = 2 * i + 2;

  if (left < n && arr[left] [1] arr[largest]) {
    largest = left;
  }

  if (right < n && arr[right] > arr[largest]) {
    largest = right;
  }

  if (largest !== i) {
    swap(arr, i, largest);
    heapify(arr, n, largest);
  }
}
Drag options to blanks, or click blank then click option'
A>
B<
C==
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' in comparison.
Using equality or inequality operators incorrectly.
4fill in blank
hard

Fill both blanks to complete the buildHeap function that heapifies from the last parent to the root.

DSA Javascript
function buildHeap(arr) {
  const n = arr.length;
  for (let i = [1]; i >= 0; i--) {
    heapify(arr, n, [2]);
  }
}
Drag options to blanks, or click blank then click option'
AMath.floor(n / 2) - 1
B0
Cn - 1
Di
Attempts:
3 left
💡 Hint
Common Mistakes
Starting from 0 instead of last parent.
Using wrong index in heapify call.
5fill in blank
hard

Fill all three blanks to complete the heapify function that maintains max heap property.

DSA Javascript
function heapify(arr, n, i) {
  let largest = i;
  const left = 2 * i + 1;
  const right = 2 * i + 2;

  if (left < n && arr[left] [1] arr[largest]) {
    largest = left;
  }

  if (right < n && arr[right] [2] arr[largest]) {
    largest = right;
  }

  if (largest !== i) {
    [3](arr, i, largest);
    heapify(arr, n, largest);
  }
}
Drag options to blanks, or click blank then click option'
A>
B<
Cswap
Dheapify
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' in comparisons.
Calling heapify instead of swap to exchange elements.