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[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[[1]];
arr[j] = temp;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using arr[i] instead of arr[j] for the swap.
Assigning arr[j] before saving temp.
✗ Incorrect
We swap arr[i] with arr[j], so arr[i] should get arr[j].
2fill in blank
mediumComplete the code to find the left child index in the heap.
DSA C#
int LeftChild(int i) {
return 2 * i [1] 1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction instead of addition.
Using multiplication twice.
✗ Incorrect
Left child index in heap is 2*i + 1.
3fill in blank
hardFix the error in the heapify function to maintain max heap property.
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] [1] arr[largest])
largest = right;
if (largest != i) {
Swap(arr, i, largest);
Heapify(arr, n, largest);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > in comparisons.
Using equality operators instead of comparison.
✗ Incorrect
To maintain max heap, we check if child is greater than current largest.
4fill in blank
hardFill both blanks to build the max heap from the array.
DSA C#
void BuildMaxHeap(int[] arr, int n) {
for (int i = n / 2 - 1; i [1] -1; i[2]) {
Heapify(arr, n, i);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using i++ instead of i-- in the loop.
Using less than instead of greater than in condition.
✗ Incorrect
We start from the last parent and move backwards, so i >= 0 and i--.
5fill in blank
hardComplete the code to complete the heap sort main loop.
DSA C#
void HeapSort(int[] arr) {
int n = arr.Length;
BuildMaxHeap(arr, n);
for (int i = n - 1; i > 0; i[1]) {
Swap(arr, 0, i);
Heapify(arr, i, 0);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using i++ instead of i-- in loop.
Missing comma between arguments in Heapify.
Missing closing parenthesis in Heapify call.
✗ Incorrect
We decrement i in loop, pass i as size to Heapify, and close the argument list with ).
