-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap_sort.cc
More file actions
32 lines (29 loc) · 779 Bytes
/
heap_sort.cc
File metadata and controls
32 lines (29 loc) · 779 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
#include "./include/sort.hh"
// Complexity O(log(n))
void max_heapify(std::vector<int>& A, int& size, int i) {
int l = left(i);
int r = right(i);
int largest = i;
if (l < size && A[l] > A[largest])
largest = l;
if (r < size && A[r] > A[largest])
largest = r;
if (largest != i) {
std::swap(A[largest], A[i]);
max_heapify(A, size, largest);
}
}
// Complexity O(n*log(n))
void build_max_heap(std::vector<int>& A) {
int size = A.size();
for (int i = A.size() >> 1; i >= 0; i--)
max_heapify(A, size, i);
}
// Complexity O(n*log(n))
void heapsort(std::vector<int>& A) {
build_max_heap(A);
for (int i = A.size() - 1; i > 0; i--) {
std::swap(A[0], A[i]);
max_heapify(A, i, 0);
}
}