#include <stdio.h>
#include <stdlib.h>
void heapify(int array[], int size, int i);
void swap(int *a, int *b);
void printArray(int array[], int size);
void insert(int array[], int newNum);
void deleteRoot(int array[], int *size);
// Global variable for tracking the size of the heap
int size = 0;
int main(void) {
int array[10];
// Inserting elements into the heap
insert(array, 3);
insert(array, 4);
insert(array, 9);
insert(array, 5);
insert(array, 2);
// Printing the Max-Heap
printArray(array, size);
// Deleting the root element
deleteRoot(array, &size);
printf("After deleting an element: "); printArray(array, size);
return 0;
}
// Function to swap two elements
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Function to heapify the array
void heapify(int array[], int size, int i) {
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // Left child
int right = 2 * i + 2; // Right child
// If left child is larger than root
if (left < size && array[left] > array[largest])
largest = left;
// If right child is larger than largest so far
if (right < size && array[right] > array[largest])
largest = right;
// If largest is not root
if (largest != i) {
swap(&array[i], &array[largest]);
// Recursively heapify the affected sub-tree
heapify(array, size, largest);
}
}
// Function to insert a new element into the heap
void insert(int array[], int newNum) {
array[size] = newNum; // Insert the new element at the end
int current = size;
size++;
// Fix the Max Heap property if it's violated
while (current != 0 && array[(current - 1) / 2] < array[current]) {
swap(&array[(current - 1) / 2], &array[current]);
current = (current - 1) / 2;
}
}
// Function to delete the root element from the heap
void deleteRoot(int array[], int *size) {
if (*size <= 0) {
return;
}
// Replace root with the last element
array[0] = array[*size - 1];
(*size)--;
// Heapify the root
heapify(array, *size, 0);
}
// Function to print the array
void printArray(int array[], int size) {
for (int i = 0; i < size; i++) {
}
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KCnZvaWQgaGVhcGlmeShpbnQgYXJyYXlbXSwgaW50IHNpemUsIGludCBpKTsKdm9pZCBzd2FwKGludCAqYSwgaW50ICpiKTsKdm9pZCBwcmludEFycmF5KGludCBhcnJheVtdLCBpbnQgc2l6ZSk7CnZvaWQgaW5zZXJ0KGludCBhcnJheVt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