fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. void heapify(int array[], int size, int i);
  5. void swap(int *a, int *b);
  6. void printArray(int array[], int size);
  7. void insert(int array[], int newNum);
  8. void deleteRoot(int array[], int *size);
  9.  
  10. // Global variable for tracking the size of the heap
  11. int size = 0;
  12.  
  13. int main(void) {
  14. int array[10];
  15.  
  16. // Inserting elements into the heap
  17. insert(array, 3);
  18. insert(array, 4);
  19. insert(array, 9);
  20. insert(array, 5);
  21. insert(array, 2);
  22.  
  23. // Printing the Max-Heap
  24. printf("Max-Heap array: ");
  25. printArray(array, size);
  26.  
  27. // Deleting the root element
  28. deleteRoot(array, &size);
  29. printf("After deleting an element: ");
  30. printArray(array, size);
  31.  
  32. return 0;
  33. }
  34.  
  35. // Function to swap two elements
  36. void swap(int *a, int *b) {
  37. int temp = *a;
  38. *a = *b;
  39. *b = temp;
  40. }
  41.  
  42. // Function to heapify the array
  43. void heapify(int array[], int size, int i) {
  44. int largest = i; // Initialize largest as root
  45. int left = 2 * i + 1; // Left child
  46. int right = 2 * i + 2; // Right child
  47.  
  48. // If left child is larger than root
  49. if (left < size && array[left] > array[largest])
  50. largest = left;
  51.  
  52. // If right child is larger than largest so far
  53. if (right < size && array[right] > array[largest])
  54. largest = right;
  55.  
  56. // If largest is not root
  57. if (largest != i) {
  58. swap(&array[i], &array[largest]);
  59. // Recursively heapify the affected sub-tree
  60. heapify(array, size, largest);
  61. }
  62. }
  63.  
  64. // Function to insert a new element into the heap
  65. void insert(int array[], int newNum) {
  66. array[size] = newNum; // Insert the new element at the end
  67. int current = size;
  68. size++;
  69.  
  70. // Fix the Max Heap property if it's violated
  71. while (current != 0 && array[(current - 1) / 2] < array[current]) {
  72. swap(&array[(current - 1) / 2], &array[current]);
  73. current = (current - 1) / 2;
  74. }
  75. }
  76.  
  77. // Function to delete the root element from the heap
  78. void deleteRoot(int array[], int *size) {
  79. if (*size <= 0) {
  80. printf("Heap is empty!\n");
  81. return;
  82. }
  83.  
  84. // Replace root with the last element
  85. array[0] = array[*size - 1];
  86. (*size)--;
  87.  
  88. // Heapify the root
  89. heapify(array, *size, 0);
  90. }
  91.  
  92. // Function to print the array
  93. void printArray(int array[], int size) {
  94. for (int i = 0; i < size; i++) {
  95. printf("%d ", array[i]);
  96. }
  97. printf("\n");
  98. }
  99.  
Success #stdin #stdout 0s 5272KB
stdin
Standard input is empty
stdout
Max-Heap array: 9 5 4 3 2 
After deleting an element: 5 3 4 2