-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxHeap.cpp
More file actions
146 lines (129 loc) · 2.29 KB
/
MaxHeap.cpp
File metadata and controls
146 lines (129 loc) · 2.29 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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#include "MaxHeap.h"
MaxHeap::~MaxHeap()
{
delete[] heap;
}
bool MaxHeap::Build(std::string filename)
{
std::fstream data(filename, std::ios::in);
if (!data)
return false;
// count the elements
std::string number = "";
while (std::getline(data, number))
currentSize++;
maxSize = currentSize + 100;
delete[] heap; // delete for safety
heap = new int[maxSize];
// Go to the start of the file
data.clear();
data.seekg(0, std::ios_base::beg);
// Fill the heap
heap[0] = -1;
int i = 1;
while (std::getline(data, number))
{
int element = std::stoi(number);
heap[i] = element;
i++;
}
for (int i = currentSize / 2; i >= 1; i--)
Heapify(i);
return true;
}
bool MaxHeap::Insert(int number)
{
if (currentSize < maxSize)
{
int pos = ++currentSize;
heap[pos] = number;
while (pos > 1 && heap[parent(pos)] < heap[pos])
{
Swap(pos, parent(pos));
pos = parent(pos);
}
return true;
}
return false;
}
bool MaxHeap::DeleteMax()
{
if (currentSize > 0)
{
int temp = heap[currentSize--];
int tempPos = 1;
int newPos = 1;
heap[1] = temp;
while (tempPos < currentSize)
{
int leftC = leftChild(tempPos);
int rightC = rightChild(tempPos);
if (leftC <= currentSize)
{
if (temp < heap[leftC])
newPos = leftC;
if (rightC <= currentSize)
if (heap[leftC] < heap[rightC])
newPos = rightC;
}
if (newPos != tempPos)
{
Swap(tempPos, newPos);
tempPos = newPos;
}
else
break;
}
return true;
}
return false;
}
int MaxHeap::GetSize() const
{
return currentSize;
}
int MaxHeap::GetMax() const
{
if (currentSize > 0)
return heap[1];
else
return -1;
}
void MaxHeap::Heapify(int level)
{
int parent = heap[level];
int leftPos = leftChild(level);
int rightPos = rightChild(level);
int maxPos = level;
if (leftPos <= currentSize)
{
if (parent < heap[leftPos])
maxPos = leftPos;
if (rightPos <= currentSize)
if (heap[maxPos] < heap[rightPos])
maxPos = rightPos;
}
if (maxPos != level)
{
Swap(maxPos, level);
Heapify(maxPos);
}
}
void MaxHeap::Swap(int i, int j)
{
int temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
}
int MaxHeap::parent(int i)
{
return i / 2;
}
int MaxHeap::leftChild(int parentPos)
{
return 2 * parentPos;
}
int MaxHeap::rightChild(int parentPos)
{
return (2 * parentPos) + 1;
}