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

Heap Sort

The document contains C code that implements the Heap Sort algorithm using a max heap. It includes functions for swapping elements, maintaining the max heap property, and sorting an array. The main function demonstrates sorting an example array and printing the sorted result.

Uploaded by

goblin3473
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)
2 views2 pages

Heap Sort

The document contains C code that implements the Heap Sort algorithm using a max heap. It includes functions for swapping elements, maintaining the max heap property, and sorting an array. The main function demonstrates sorting an example array and printing the sorted result.

Uploaded by

goblin3473
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

#include <stdio.

h>

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


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

void maxHeapify(int arr[], int n, int i) {


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

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


largest = left;

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


largest = right;

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

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


// Build a max heap
for (int i = n / 2 - 1; i >= 0; i--)
maxHeapify(arr, n, i);
// Extract elements from the heap one by one
for (int i = n - 1; i > 0; i--) {
swap(&arr[0], &arr[i]);
maxHeapify(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[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);

heapSortMax(arr, n);

printf("Sorted array (Max HeapSort): \n");


printArray(arr, n);

return 0;
}

You might also like