Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to swap two elements in the array.
DSA C++
void swap(int& a, int& b) {
int temp = a;
a = [1];
b = temp;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning 'a' to 'temp' again instead of 'b'.
Using '0' instead of 'b'.
✗ Incorrect
The swap function exchanges the values of a and b by using a temporary variable. After storing a in temp, a should be assigned the value of b.
2fill in blank
mediumComplete the code to heapify a subtree rooted with index i.
DSA C++
void heapify(int arr[], int n, int i) {
int largest = i;
int left = 2 * i + 1;
int 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], arr[largest]);
heapify(arr, n, largest);
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' causing min-heap behavior.
Using '==' which does not help in comparison.
✗ Incorrect
To maintain max-heap property, we check if the left child is greater than the current largest element.
3fill in blank
hardFix the error in the loop that builds the heap.
DSA C++
for (int i = n / 2 - 1; i >= [1]; i--) { heapify(arr, n, i); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'n' or '1' as the stopping condition causes out-of-bound errors.
Using '-1' skips the root node.
✗ Incorrect
Heap building starts from the last non-leaf node down to the root at index 0.
4fill in blank
hardFill both blanks to complete the heap sort extraction loop.
DSA C++
for (int i = n - 1; i > [1]; i--) { swap(arr[0], arr[i]); heapify(arr, i, [2]); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'i' or 'n' in place of 0 causes incorrect heapify calls.
Stopping loop at wrong index skips sorting.
✗ Incorrect
The loop runs until i > 0, and after swapping, heapify is called on the root index 0 with reduced heap size i.
5fill in blank
hardFill all three blanks to complete the heap sort function.
DSA C++
void heapSort(int arr[], int n) {
for (int i = n / 2 - 1; i >= [1]; i--) {
heapify(arr, n, i);
}
for (int i = n - 1; i > [2]; i--) {
swap(arr[[3]], arr[i]);
heapify(arr, i, 0);
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 or n instead of 0 for root index.
Incorrect loop stopping conditions.
✗ Incorrect
The first loop builds the heap starting from index 0. The second loop extracts elements until i > 0. The swap uses index 0 as the root.