-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap_sort.c
110 lines (88 loc) · 1.84 KB
/
heap_sort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <stdio.h>
int left(int i);
int right(int i);
int parent(int i);
void max_heapify(int arr[], int heap_size, int i); // Complexity : O(log n)
void heap_print(int heap[], int heap_size);
void build_max_heap(int heap[], int heap_size);
void heap_sort_algorithm(int heap[], int heap_size); // Complexity : O(n log n)
int main(void)
{
int H[] = {0, 2, 1, 7, 3, 19, 17, 10, 12, 5};
int size = ((sizeof(H)/sizeof(H[0])) - 1);
heap_print(H, size);
printf("\n\n");
build_max_heap(H, size);
heap_print(H, size);
printf("\n\n");
// Sort Algo
heap_sort_algorithm(H, size);
heap_print(H, size);
return 0;
}
// add left
int left(int i)
{
return 2*i;
}
// add right
int right(int i)
{
return 2*i+1;
}
// search parent
int parent(int i)
{
return i/2;
}
// max heapify
void max_heapify(int arr[], int heap_size, int i)
{
int l, r, largest, temp;
l = left(i);
r = right(i);
if(l <= heap_size && arr[l] > arr[i])
largest = l;
else
largest = i;
if(r <= heap_size && arr[r] > arr[largest])
largest = r;
if(largest != i)
{
temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
max_heapify(arr, heap_size, largest);
}
}
// print heap
void heap_print(int heap[], int heap_size)
{
int i;
for(i = 1; i <= heap_size; i++)
{
printf("%d ", heap[i]);
}
}
// build max heap
void build_max_heap(int heap[], int heap_size)
{
int i;
for(i = heap_size/2; i >= 1; i--)
{
max_heapify(heap, heap_size, i);
}
}
// Heap sort Algorithm
void heap_sort_algorithm(int heap[], int heap_size)
{
int i, temp;
for(i = heap_size; i > 1; i--)
{
temp = heap[1];
heap[1] = heap[i];
heap[i] = temp;
heap_size -= 1;
max_heapify(heap, heap_size, 1);
}
}