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

Heap Sort Algorithm in C Code

The document contains a C program that implements the Heap Sort algorithm. It includes functions for heapifying an array, sorting the array using heap sort, and printing the sorted array. The main function demonstrates the sorting of a predefined array of integers.

Uploaded by

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

Heap Sort Algorithm in C Code

The document contains a C program that implements the Heap Sort algorithm. It includes functions for heapifying an array, sorting the array using heap sort, and printing the sorted array. The main function demonstrates the sorting of a predefined array of integers.

Uploaded by

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

Program 5: Program For Heap Sort

#include <stdio.h>
#include<conio.h>
void heapify(int arr[], int n, int i) {

// Initialize largest as root


int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;

if (l < n && arr[l] > arr[largest]) {


largest = l;
}
if (r < n && arr[r] > arr[largest]) {
largest = r;
}

// If largest is not root


if (largest != i) {
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;

heapify(arr, n, largest);
}
}
void heapSort(int arr[], int n) {
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
for (int i = n - 1; i > 0; i--) {
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
heapify(arr, i, 0);
}
}

void printArray(int arr[], int n) {


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {9, 4, 3, 8, 10, 2, 5};
int n = sizeof(arr) / sizeof(arr[0]);

heapSort(arr, n);

printf("Sorted array is \n");


printArray(arr, n);
return 0;
}

Output:

You might also like