0% found this document useful (0 votes)
5 views1 page

Heapsort Program

The document contains a C program that implements the Heap Sort algorithm. It includes functions for heapifying an array, sorting the array using heapsort, swapping elements, and printing the array. The program demonstrates sorting an example array and outputs the array before and after sorting.

Uploaded by

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

Heapsort Program

The document contains a C program that implements the Heap Sort algorithm. It includes functions for heapifying an array, sorting the array using heapsort, swapping elements, and printing the array. The program demonstrates sorting an example array and outputs the array before and after sorting.

Uploaded by

anshikay2609
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Heap Sort Program in C

#include <stdio.h>

// function prototypes
void heapify(int* arr, int n, int i);
void heapsort(int* arr, int n);
void print_array(int* arr, int n);
void swap(int* a, int* b);

void main() {
int arr[] = {10, 30, 5, 63, 22, 12, 56, 33};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Array before sorting:\n");


print_array(arr, n);

heapsort(arr, n);

printf("\nArray after sorting:\n");


print_array(arr, n);
}

// Heap Sort main function


void heapsort(int* arr, int n) {
// Build max heap
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}

// Extract elements from heap


for (int i = n - 1; i > 0; i--) {
swap(&arr[0], &arr[i]); // move current root to end
heapify(arr, i, 0); // heapify reduced heap
}
}

// Heapify a subtree rooted at i


void heapify(int* arr, int n, int i) {
int maxIndex = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < n && arr[left] > arr[maxIndex])


maxIndex = left;

if (right < n && arr[right] > arr[maxIndex])


maxIndex = right;

if (maxIndex != i) {
swap(&arr[i], &arr[maxIndex]);
heapify(arr, n, maxIndex);
}
}

// Swap helper
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}

// Print array
void print_array(int* arr, int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

You might also like