-
Notifications
You must be signed in to change notification settings - Fork 54
/
Heapsort.h
76 lines (63 loc) · 1.58 KB
/
Heapsort.h
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
//
// heapsort running time is O(nlgn)
// This is max_heap building and heapsort return ascending order
//
#ifndef HEAPSORT_H
#define HEAPSORT_H
#include <vector>
#include <iostream>
#include <math.h>
#include <algorithm>
template <typename comparable> class heapsort {
public:
heapsort(){};
void max_heapify(std::vector<comparable> &A, const int i) {
int l = LEFT(i);
int r = RIGHT(i);
int largest;
if (l < heapSize && A[l] > A[i]) {
largest = l;
} else largest = i;
if (r < heapSize && A[r] > A[largest]) {
largest = r;
}
if (largest != i) {
swap(A[i], A[largest]);
max_heapify(A, largest);
}
}
void build_max_heap(std::vector<comparable> &A) {
heapSize = A.size();
for (int i = floor(A.size() / 2); i >= 0; i--) {
max_heapify(A, i);
}
}
void heapsort(std::vector<comparable> &A) {
build_max_heap(A);
for (int i = A.size() - 1; i >= 1; i--) {
swap(A[0], A[i]);
heapSize--;
max_heapify(A, 0);
}
}
inline int LEFT(const int i) {
return (i << 1);
}
inline int RIGHT(const int i) {
return (i << 1) + 1;
}
inline int PARENT(const int i) {
return floor(i >> 1);
}
void swap(comparable &a, comparable &b) {
comparable temp = b;
b = a;
a = temp;
}
int& getHeapSize() {
return heapSize;
}
private:
int heapSize = 0;
};
#endif