-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPriorityQueue.cpp
106 lines (106 loc) · 1.98 KB
/
PriorityQueue.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
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
#include<iostream>
#include "PriorityQueue.h"
using namespace std;
namespace Hofman
{
PriorityQueue::PriorityQueue(HoffmanNode** unsortedarr,int size)
{
allocated = false;
maxSize = this->size = size;
data = unsortedarr;
this->size = size;
floydBuild();
}
PriorityQueue::~PriorityQueue()
{
makeEmpty();
}
void PriorityQueue::makeEmpty()
{
if (allocated)
{
for (int i = 0; i < size; i++)
delete data[i];
delete[]data;
}
data = nullptr;
size = 0;
}
bool PriorityQueue::isEmpty()const
{
if (size == 0)
return true;
else return false;
}
void PriorityQueue::floydBuild()
{
for (int i = size / 2 - 1; i >= 0; i--)
fixHeap(i);
}
void PriorityQueue::Insert(HoffmanNode* toinsert)
{
if (size == maxSize)
{
cout << "input error";
exit(0);
}
int i = size;
size++;
while (i > 0 && data[Parent(i)]->getFreq() > toinsert->getFreq())
{
data[i] = data[Parent(i)];
i = Parent(i);
}
data[i] = toinsert;
}
HoffmanNode* PriorityQueue::deleteMin()
{
if (size < 1)
{
cout << "invalid input";
exit(1);
}
HoffmanNode* min = data[0];
size--;
data[0] = data[size];
fixHeap(0);
return min;
}
const int PriorityQueue::Parent(int node)const
{
return (node - 1) / 2;
}
const int PriorityQueue::Left(int node)const
{
return (2 * node) + 1;
}
const int PriorityQueue::Right(int node)const
{
return (2 * node) + 2;
}
void PriorityQueue::fixHeap(int node)
{
int min;
int left = Left(node);
int right = Right(node);
if (left < size && (data[left]->getFreq() < data[node]->getFreq()))
min = left;
else min = node;
if (right < size)
{
if (data[right]->getFreq() < data[min]->getFreq())
min = right;
}
if (min != node)
{
Swap(data[node], data[min]);
fixHeap(min);
}
}
void PriorityQueue::Swap(HoffmanNode*& a, HoffmanNode*& b)
{
HoffmanNode* temp = a;
a = b;
b = temp;
}
}