0
0
DSA Javascriptprogramming~10 mins

Heap Sort Algorithm 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 swap two elements in the array.

DSA Javascript
function swap(arr, i, j) {
  let temp = arr[i];
  arr[i] = arr[1]j;
  arr[j] = temp;
}
Drag options to blanks, or click blank then click option'
A+
B-
C[
D.
Attempts:
3 left
💡 Hint
Common Mistakes
Using dot notation instead of square brackets to access array elements.
Using plus or minus signs which are arithmetic operators, not for indexing.
2fill in blank
medium

Complete the code to heapify a subtree rooted at index i.

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

  if (left < n && arr[left] > 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'
A0
B3
C1
D2
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 instead of 2 for the right child index.
Using 3 or 0 which are incorrect for child indexing.
3fill in blank
hard

Fix the error in the loop that builds the max heap.

DSA Javascript
for (let i = Math.floor(n / 2) - 1; i [1] 0; i--) {
  heapify(arr, n, i);
}
Drag options to blanks, or click blank then click option'
A>=
B<=
C<
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' or '<=' which causes the loop to skip the root node.
Using '>' which causes an infinite loop.
4fill in blank
hard

Fill both blanks to complete the heap sort main loop.

DSA Javascript
for (let i = n - 1; i > [1]; i--) {
  swap(arr, 0, i);
  heapify(arr, i, [2]);
}
Drag options to blanks, or click blank then click option'
A0
B1
Ci
Dn
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 or n instead of 0 for heapify starting index.
Using i instead of 0 for heapify starting index.
5fill in blank
hard

Fill all three blanks to complete the heap sort function.

DSA Javascript
function heapSort(arr) {
  let n = arr.length;

  for (let i = Math.floor(n / 2) - 1; i [1] 0; i--) {
    heapify(arr, n, i);
  }

  for (let i = n - 1; i > [2]; i--) {
    swap(arr, 0, i);
    heapify(arr, i, [3]);
  }
}
Drag options to blanks, or click blank then click option'
A>=
B>
C0
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' or '<=' in the first loop condition.
Using 1 instead of 0 for heapify starting index.
Using '>=' instead of '>' in the second loop condition.