Complete the code to swap two elements in the array.
int temp = arr[[1]]; arr[[1]] = arr[j]; arr[j] = temp;
j instead of i causes swapping the same element.0 or n causes index errors.The variable i is used to swap the element at index i with the element at index j.
Complete the code to find the left child index in the heap.
int left = 2 * i [1] 1;
- instead of addition.The left child index in a heap is calculated as 2 * i + 1.
Fix the error in the condition to check if right child exists in the heap.
if (right [1] n && arr[right] > arr[largest]) {
The right child index must be less than n to exist in the heap.
Fill both blanks to complete the heapify recursive call and swap.
if (largest != i) { int swap = arr[i]; arr[i] = arr[[1]]; arr[[2]] = swap; heapify(arr, n, largest); }
i or n instead of largest in swap causes incorrect heap structure.We swap the element at i with the element at largest, then recursively heapify at largest.
Fill all three blanks to complete the heap sort main loop.
for (int i = n - 1; i > 0; i--) { int temp = arr[0]; arr[0] = arr[[1]]; arr[[2]] = temp; heapify(arr, [3], 0); }
n instead of i in swap or heapify causes wrong sorting.0 twice does nothing.Swap the root arr[0] with arr[i], then heapify the reduced heap of size i.
