-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathheapsort.hpp
More file actions
40 lines (36 loc) · 818 Bytes
/
heapsort.hpp
File metadata and controls
40 lines (36 loc) · 818 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
/*template <class T>
void swap(T& a, T& b) {
T t(a);
a = b;
b = t;
}*/
template <class T>
void max_heapify(T a[], size_t size, size_t i) {
size_t left = (i + 1) * 2 - 1;
size_t right = (i + 1) * 2;
size_t largest = i;
if (left < size && a[left] > a[largest])
largest = left;
if (right < size && a[right] > a[largest])
largest = right;
if (largest != i) {
swap(a[i], a[largest]);
max_heapify(a, size, largest);
}
}
template <class T>
void build_max_heap(T a[], size_t size) {
for (int i = size / 2; i >= 0; i--) {
max_heapify(a, size, i);
}
}
template <class T>
void heapsort(T a[], size_t size) {
build_max_heap(a, size);
size_t heap_size = size;
for (int i = size-1; i > 0; i--) {
swap(a[0], a[i]);
heap_size--;
max_heapify(a, heap_size, 0);
}
}