forked from ddhira123/Algorithms-HacktoberFest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap_sort.cpp
More file actions
42 lines (32 loc) · 792 Bytes
/
heap_sort.cpp
File metadata and controls
42 lines (32 loc) · 792 Bytes
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
// HEAP SORT
// To use this, call heap_sort() with a unsorted int*. Make sure ANT equals the size
// of this array.
const int ANT = 8;
void swap(int *arr, int r1, int r2) {
int t = arr[r1];
arr[r1] = arr[r2];
arr[r2] = t;
}
void heapify(int *arr, int ant, int i) {
int largest = i;
// Find the children of this root
int left = 2 * i;
int right = 2 * i + 1;
if (left <= ant && arr[left] > arr[largest])
largest = left;
if (right <= ant && arr[right] > arr[largest])
largest = right;
if (largest != i) {
swap(arr, i, largest);
heapify(arr, ant, largest);
}
}
void heap_sort(int *arr) {
for (int i = ANT / 2; i >= 1; i--) {
heapify(arr, ANT, i);
}
for (int i = ANT; i >= 1; i--) {
swap(arr, 1, i);
heapify(arr, i - 1, 1);
}
}