0% found this document useful (0 votes)
12 views2 pages

Heap Sort Jisan.c

The document describes functions for implementing a max heap data structure including insert, deleteRoot, heapify and printHeap functions. It defines a max size, uses swapping to maintain the heap property, and includes a main function to test the heap operations.

Uploaded by

Md Jisan Mia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views2 pages

Heap Sort Jisan.c

The document describes functions for implementing a max heap data structure including insert, deleteRoot, heapify and printHeap functions. It defines a max size, uses swapping to maintain the heap property, and includes a main function to test the heap operations.

Uploaded by

Md Jisan Mia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>

#define MAX_SIZE 10

int heap_size = 0;

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

void heapify(int array[], int heap_size, int i) {


int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < heap_size && array[left] > array[largest])


largest = left;

if (right < heap_size && array[right] > array[largest])


largest = right;

if (largest != i) {
swap(&array[i], &array[largest]);
heapify(array, heap_size, largest);
}
}

void insert(int array[], int new_element) {


if (heap_size >= MAX_SIZE) {
printf("Heap is full, cannot insert element.\n");
return;
}

array[heap_size] = new_element;
heap_size++;

for (int i = heap_size / 2 - 1; i >= 0; i--) {


heapify(array, heap_size, i);
}
}

void deleteRoot(int array[], int element_to_delete) {


int i;
for (i = 0; i < heap_size; i++) {
if (array[i] == element_to_delete)
break;
}

if (i == heap_size) {
printf("Element not found in the heap.\n");
return;
}

swap(&array[i], &array[heap_size - 1]);


heap_size--;

for (int i = heap_size / 2 - 1; i >= 0; i--) {


heapify(array, heap_size, i);
}
}

void printHeap(int array[], int heap_size) {


for (int i = 0; i < heap_size; i++) {
printf("%d ", array[i]);
}
printf("\n");
}

int main() {
int heap[MAX_SIZE] = {0};

insert(heap, 3);
insert(heap, 4);
insert(heap, 9);
insert(heap, 5);
insert(heap, 2);

printHeap(heap, heap_size);

deleteRoot(heap, 4);
printf("After deleting element 4:\n");
printHeap(heap, heap_size);

return 0;
}

You might also like