0
0
DSA C++programming~10 mins

Heap Sort Algorithm in DSA C++ - 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 C++
void swap(int& a, int& b) {
    int temp = a;
    a = [1];
    b = temp;
}
Drag options to blanks, or click blank then click option'
Aa
Bb
Ctemp
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning 'a' to 'temp' again instead of 'b'.
Using '0' instead of 'b'.
2fill in blank
medium

Complete 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'
A<
B==
C>
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' causing min-heap behavior.
Using '==' which does not help in comparison.
3fill in blank
hard

Fix 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'
A0
B-1
Cn
D1
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.
4fill in blank
hard

Fill 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'
A0
Bi
C1
Dn
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.
5fill in blank
hard

Fill 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'
A0
B1
Dn
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 or n instead of 0 for root index.
Incorrect loop stopping conditions.