-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap.cc
More file actions
124 lines (110 loc) · 2.66 KB
/
heap.cc
File metadata and controls
124 lines (110 loc) · 2.66 KB
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
// Author: krems
#include <vector>
#include <stdlib.h>
#include <iostream>
using std::vector;
template <typename T>
class Heap {
vector<T> _data;
public:
Heap() {}
template <size_t N>
explicit Heap(T (&data)[N]) {
makeHeap<N>(data);
}
explicit Heap(const vector<T>& data) {
makeHeap(data);
}
void makeHeap(vector<T> data) {
_data = data;
for (int i = _data.size(); i >= 0; --i) {
heapify(i);
}
}
template<size_t N>
void makeHeap(T (&data)[N]) {
_data = vector<T>(data, data + N);
for (int i = _data.size(); i >= 0; --i) {
heapify(i);
}
}
const T& peek() const {
return _data[0];
}
void add(const T& element) {
_data.push_back(element);
size_t el_position = _data.size() - 1;
size_t parent_position = (el_position - 1) / 2;
while (el_position > 0 && _data[parent_position] < _data[el_position]) {
std::swap(_data[parent_position], _data[el_position]);
el_position = parent_position;
parent_position = (el_position - 1) / 2;
}
}
T pop() {
T tmp = _data[0];
_data[0] = *(_data.end() - 1);
_data.pop_back();
heapify(0);
return tmp;
}
~Heap() {}
private:
void heapify(size_t vertex) {
size_t left = 2 * vertex + 1;
size_t right = 2 * vertex + 2;
if (left >= _data.size() || right >= _data.size()) {
return;
}
if (_data[vertex] < _data[left] || _data[vertex] < _data[right]) {
size_t max_child_position = left;
if (_data[left] < _data[right]) {
max_child_position = right;
}
std::swap(_data[vertex], _data[max_child_position]);
heapify(max_child_position);
}
}
};
template <typename T, size_t N>
void heapSort(T (&array)[N]) {
if (N == 0) {
return;
}
Heap<T> heap(array);
for (int i = N - 1; i >= 0; --i) {
array[i] = heap.pop();
}
}
template <typename T>
void heapSort(vector<T>& array) {
if (array.size() == 0) {
return;
}
Heap<T> heap(array);
for (int i = array.size() - 1; i >= 0; --i) {
array[i] = heap.pop();
}
}
int main() {
vector<int> arr {9, 8, 10, 99, 100, 0};
for (auto i = 0; i < 6; ++i) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
heapSort(arr);
for (auto i = 0; i < 6; ++i) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
int array[] = {9, 8, 10, 99, 100, 0};
for (auto i = 0; i < 6; ++i) {
std::cout << array[i] << " ";
}
std::cout << std::endl;
heapSort(array);
for (auto i = 0; i < 6; ++i) {
std::cout << array[i] << " ";
}
std::cout << std::endl;
}