-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinHeap.cpp
More file actions
147 lines (129 loc) · 2.29 KB
/
MinHeap.cpp
File metadata and controls
147 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
147
#include "MinHeap.h"
MinHeap::~MinHeap()
{
delete[] heap;
}
bool MinHeap::Build(std::string filename)
{
std::ifstream data(filename);
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 start of 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 MinHeap::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 MinHeap::DeleteMin()
{
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 MinHeap::GetSize() const
{
return currentSize;
}
int MinHeap::GetMin() const
{
if (currentSize > 0)
return heap[1];
else
return -1;
}
void MinHeap::Heapify(int level)
{
int parent = heap[level];
int leftPos = leftChild(level);
int rightPos = rightChild(level);
int minPos = level;
if (leftPos <= currentSize)
{
if (parent > heap[leftPos])
minPos = leftPos;
if (rightPos <= currentSize)
if (heap[minPos] > heap[rightPos])
minPos = rightPos;
}
if (minPos != level)
{
Swap(minPos, level);
Heapify(minPos);
}
}
void MinHeap::Swap(int i, int j)
{
int temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
}
int MinHeap::parent(int i) const
{
return i / 2;
}
int MinHeap::leftChild(int parentPos) const
{
return 2 * parentPos;
}
int MinHeap::rightChild(int parentPos) const
{
return (2 * parentPos) + 1;
}