Skip to content

Commit 690beef

Browse files
committed
Added Heapsort for C
1 parent 0ce6e1e commit 690beef

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

src/c/Heapsort.c

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#include <stdio.h>
2+
3+
void heapify(int arr[], int n, int i)
4+
{
5+
int largest = i;
6+
int left = 2 * i + 1;
7+
int right = 2 * i + 2;
8+
9+
if (left < n && arr[left] > arr[largest])
10+
largest = left;
11+
12+
// If the right child is larger than the largest so far
13+
if (right < n && arr[right] > arr[largest])
14+
largest = right;
15+
16+
// If the largest element is not the root
17+
if (largest != i)
18+
{
19+
// Swap the largest element with the root
20+
int temp = arr[i];
21+
arr[i] = arr[largest];
22+
arr[largest] = temp;
23+
24+
// Recursively heapify the affected sub-tree
25+
heapify(arr, n, largest);
26+
}
27+
}
28+
29+
void heapsort(int arr[], int n)
30+
{
31+
// Build a max heap
32+
int i;
33+
for (i = n / 2 - 1; i >= 0; i--)
34+
heapify(arr, n, i);
35+
36+
// One by one extract elements from the heap
37+
for (i = n - 1; i > 0; i--)
38+
{
39+
// Move the current root to the end
40+
int temp = arr[0];
41+
arr[0] = arr[i];
42+
arr[i] = temp;
43+
44+
// Call max heapify on the reduced heap
45+
heapify(arr, i, 0);
46+
}
47+
}
48+
49+
int main()
50+
{
51+
int arr[] = {12, 21, 13, 5, 1, 7};
52+
int i;
53+
int n = sizeof(arr) / sizeof(arr[0]);
54+
55+
printf("Original array: ");
56+
for (i = 0; i < n; i++)
57+
printf("%d ", arr[i]);
58+
59+
heapsort(arr, n);
60+
61+
printf("\nSorted array: ");
62+
for (i = 0; i < n; i++)
63+
printf("%d ", arr[i]);
64+
65+
return 0;
66+
}

0 commit comments

Comments
 (0)