Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to get the index of the left child in a heap array.
DSA Java
int leftChild(int i) {
return 2 * i [1] 1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction instead of addition.
Using multiplication or division incorrectly.
✗ Incorrect
In a heap stored as an array, the left child of node at index i is at 2*i + 1.
2fill in blank
mediumComplete the code to swap two elements in the array.
DSA Java
void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[[1]];
arr[[1]] = temp;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using the same index i for both assignments.
Using invalid indices like 0 or arr.length.
✗ Incorrect
To swap elements at i and j, assign arr[i] = arr[j] and arr[j] = temp.
3fill in blank
hardFix the error in the heapify method to correctly heapify the subtree rooted at index i.
DSA Java
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, largest);
heapify(arr, n, largest);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>'.
Using equality or inequality operators incorrectly.
✗ Incorrect
To maintain max-heap property, we check if left child is greater than current largest.
4fill in blank
hardFill both blanks to complete the buildHeap method that builds a max heap from an array.
DSA Java
void buildHeap(int[] arr, int n) {
for (int i = [1]; i >= 0; i--) {
heapify(arr, n, [2]);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Starting from 0 instead of n/2 - 1.
Passing wrong index to heapify.
✗ Incorrect
We start heapifying from the last non-leaf node at n/2 - 1 down to 0, calling heapify at index i.
5fill in blank
hardFill all three blanks to complete the heap sort method using buildHeap and heapify.
DSA Java
void heapSort(int[] arr) {
int n = arr.length;
buildHeap(arr, n);
for (int i = n - 1; i > [1]; i--) {
swap(arr, 0, i);
heapify(arr, i, [2]);
}
// After sorting, the array is in ascending order
// The root index is [3] for heapify after swap
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong loop condition.
Heapifying wrong index after swap.
✗ Incorrect
In heap sort, we swap root with last element, then heapify root (index 0) for reduced heap size i, looping until i > 0.
