heap
heap
of the
Heap.
Description:- A heap is a data structure like a tree with some special properties. The basic requirement
of the heap is that the value of a node must be greater than equal to (or smaller than equal to) the value
of its children and the tree should be a complete binary tree.
Program:-
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int size;
int arr[MAX];
} Heap;
*a = *b;
*b = temp;
int smallest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
smallest = left;
smallest = right;
if (smallest != i) {
swap(&heap->arr[i], &heap->arr[smallest]);
minHeapify(heap, smallest);
}
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
largest = left;
largest = right;
if (largest != i) {
swap(&heap->arr[i], &heap->arr[largest]);
maxHeapify(heap, largest);
if (heap->size == MAX) {
printf("Heap is full\n");
return;
heap->size++;
int i = heap->size - 1;
heap->arr[i] = key;
i = (i - 1) / 2;
}
void insertMaxHeap(Heap *heap, int key) {
if (heap->size == MAX) {
printf("Heap is full\n");
return;
heap->size++;
int i = heap->size - 1;
heap->arr[i] = key;
i = (i - 1) / 2;
int i;
if (heap->arr[i] == key)
break;
if (i == heap->size) {
return -1;
heap->size--;
heapify(heap, i);
return 0;
printf("\n");
int main() {
insertMinHeap(&minHeap, 3);
insertMinHeap(&minHeap, 1);
insertMinHeap(&minHeap, 6);
insertMinHeap(&minHeap, 5);
insertMinHeap(&minHeap, 9);
insertMinHeap(&minHeap, 8);
insertMaxHeap(&maxHeap, 3);
insertMaxHeap(&maxHeap, 1);
insertMaxHeap(&maxHeap, 6);
insertMaxHeap(&maxHeap, 5);
insertMaxHeap(&maxHeap, 9);
insertMaxHeap(&maxHeap, 8);
displayHeap(&minHeap);
displayHeap(&maxHeap);
deleteElement(&minHeap, 5, minHeapify);
deleteElement(&maxHeap, 5, maxHeapify);
displayHeap(&minHeap);
displayHeap(&maxHeap);
return 0;
Output:-
Min Heap: 1 3 6 5 9 8
Max Heap: 9 8 6 1 5 3