Complete the code to swap two elements in the array.
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = [1];
}The variable temp temporarily holds the value of *a so that *b can be assigned to *a without losing the original value. Then *b is assigned the value stored in temp.
Complete the code to heapify a subtree rooted with index i in array of size n.
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] > arr[[1]])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i) {
swap(&arr[i], &arr[largest]);
heapify(arr, n, largest);
}
}We compare the left child arr[left] with the root arr[i] to find the largest value.
Fix the error in the loop that builds the heap from the array.
for (int i = n / 2 - 1; i >= [1]; i--) { heapify(arr, n, i); }
The loop must run from the last non-leaf node down to index 0 to build the max heap correctly.
Fill both blanks to complete the heap sort extraction loop.
for (int i = n - 1; i > [1]; i--) { swap(&arr[0], &arr[[2]]); heapify(arr, i, 0); }
The loop runs until i > 0 and swaps the root arr[0] with the last element arr[i] before heapifying the reduced heap.
Fill all three blanks to complete the heap sort function.
void heapSort(int arr[], int n) {
for (int i = n / 2 - 1; i >= [1]; i--) {
heapify(arr, n, [2]);
}
for (int i = n - 1; i > [3]; i--) {
swap(&arr[0], &arr[i]);
heapify(arr, i, 0);
}
}The first loop heapifies from last non-leaf node down to 0. The second loop extracts elements until i > 0.
