# Heap Sort in C

Feb 10, 2023
``` A simple implementation of heap sort algorithm in C programming language.

I am currently accepting programming work, IT projects, school and application development, programming projects, thesis and capstone projects, IT consulting work, computer tutorials, and web development work kindly contact me at the following email address for further details.  If you want to advertise on my website kindly contact me also in my email address also. Thank you.

My mobile number here in the Philippines is 09173084360.

=================================================

You can buy my C++ book online at

Beginner’s Guide To C++ Programming

You can buy my book in introduction to computer networking at

https://www.unlimitedbooksph.com/product-page/introduction-to-computer-networking

Want to support my channel?

GCash Account

09173084360

Paypal

Patreon

Thank you very much for your support.```
``````#include <stdio.h>

void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}

void compare(int arr[], int n, int i) {
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 != i) {
swap(&arr[i], &arr[largest]);
compare(arr, n, largest);
}
}

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

for (i = n - 1; i >= 0; i--) {
swap(&arr[0], &arr[i]);
compare(arr, i, 0);
}
}

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

int main() {
int array_values[] = {100, -45, 5, -67, 2, 16,877,-567};

int n = sizeof(array_values) / sizeof(array_values[0]);

printf("\n\n");
printf("\tHeap Sort in C\n\n\n");
printf("\tBefore Sorting\n\n");
printArrays(array_values, n);

printf("\n\n");
heapSort(array_values, n);

printf("\tAfter Sorting\n\n");
printArrays(array_values, n);
printf("\n\n");
printf("\tEnd of Program\n");
return 0;
}
``````