Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
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.
✗ Incorrect
We use square brackets to access array elements by index in JavaScript.
2fill in blank
mediumComplete 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'
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.
✗ Incorrect
The right child index in a heap is calculated as 2 * i + 2, so the blank should be 2.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' or '<=' which causes the loop to skip the root node.
Using '>' which causes an infinite loop.
✗ Incorrect
The loop should run while i is greater than or equal to 0 to cover all parent nodes.
4fill in blank
hardFill 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'
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.
✗ Incorrect
We swap the root (index 0) with the last element and then heapify from the root (index 0).
5fill in blank
hardFill 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'
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.
✗ Incorrect
The first loop runs while i >= 0, the second while i > 0, and heapify starts at index 0.