-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaxHeap.cpp
executable file
·70 lines (66 loc) · 1.54 KB
/
maxHeap.cpp
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
#include <iostream>
#include <stdexcept>
using namespace std;
template <typename DataType>
class maxHeap {
public:
maxHeap() {
array = NULL;
iterator = 0;
}
void createEmptyTree(int newSize) {
array = new DataType [newSize];
iterator = 0;
maxSize = newSize;
}
void add(DataType newNode) {
if (iterator == maxSize)
throw std::invalid_argument("Array is full");
array[iterator] = newNode;
int tmp = iterator;
while (((tmp-1)/2) >= 0 and array[tmp] > array[(tmp-1)/2]) {
swap(array[tmp], array[(tmp-1)/2]);
tmp = (tmp-1)/2;
}
iterator++;
return;
}
DataType removeRoot() {
if (iterator <= 0)
throw std::invalid_argument("Array is empty");
DataType result = array[0];
swap(array[0], array[iterator-1]);
int tmp = 0;
iterator--;
while(tmp < iterator) {
if (2*tmp+1 < iterator and array[tmp] < array[2*tmp+1] and (2*tmp+2 >= iterator or array[2*tmp+2] <= array[2*tmp+1])) {
swap(array[tmp], array[2*tmp+1]);
tmp = 2*tmp+1;
} else if (2*tmp+2 < iterator and array[tmp] < array[2*tmp+2] and array[2*tmp+2] > array[2*tmp+1]) {
swap(array[tmp], array[2*tmp+2]);
tmp = 2*tmp+2;
} else {
break;
}
}
return result;
}
int size() {
return iterator;
;
}
bool isEmpty() {
return ((iterator == 0)?true: false);
;
}
void levelOrderTraverse(int curr = 0) {
for (int i = 0; i < iterator; ++i) {
cout << array[i].first << " " << i << " " << endl;
}
return;
}
private:
DataType* array;
int iterator;
int maxSize;
};