Skip to content

Commit c6cacf3

Browse files
authored
Merge pull request kelvins#319 from JMJ2312/heapsort/in-c
Heapsort/in c
2 parents 4263e17 + d64bd59 commit c6cacf3

File tree

2 files changed

+68
-2
lines changed

2 files changed

+68
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3029,8 +3029,8 @@ In order to achieve greater coverage and encourage more people to contribute to
30293029
<tr>
30303030
<td><a href="https://en.wikipedia.org/wiki/Heapsort">Heapsort</a></td>
30313031
<td> <!-- C -->
3032-
<a href="./CONTRIBUTING.md">
3033-
<img align="center" height="25" src="./logos/github.svg" />
3032+
<a href="./src/c/Heapsort.c">
3033+
<img align="center" height="25" src="./logos/c.svg" />
30343034
</a>
30353035
</td>
30363036
<td> <!-- C++ -->

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)