forked from patricksheehan/Huffman-Compression
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhuff.cpp
70 lines (60 loc) · 1.69 KB
/
huff.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
// Patrick Sheehan
#include "huff.h"
#include <iostream>
using namespace std;
void Node:: fillCodebook(string * codebook, string &code) {
if(!leftC && !rightC){
codebook[data] = code;
return;
}
if(leftC){
code += '0';
leftC->fillCodebook(codebook, code);
code.erase(code.end()-1);
}
if(rightC){
code += '1';
rightC->fillCodebook(codebook, code);
code.erase(code.end()-1);
}
}
Node:: Node(Node * rc, Node * lc){
frequency = rc->frequency + lc->frequency;
rightC = rc;
leftC = lc;
min = (rc->min < lc->min) ? rc->min : lc->min;
}
void Heap:: push(Node *newNode) {
int currentHeapNode = ++heapSize;
while (currentHeapNode != 1 && *minHeap[currentHeapNode / 2] > *newNode) {
minHeap[currentHeapNode] = minHeap[currentHeapNode / 2];
currentHeapNode = currentHeapNode / 2;
}
minHeap[currentHeapNode] = newNode;
}
void Heap:: pop(){
Node *lastNode = minHeap[heapSize];
minHeap [heapSize--] = minHeap[1];
int currentHeapNode = 1;
int child = 2;
while (child <= heapSize) {
if (child < heapSize && *minHeap[child] > *minHeap[child + 1])
child++;
if (*minHeap[child] > *lastNode)
break;
minHeap[currentHeapNode] = minHeap[child];
currentHeapNode = child;
child *= 2;
} // while not at end of heap
minHeap[currentHeapNode] = lastNode;
}
bool Node::operator> (const Node &rhs){
if(frequency > rhs.frequency)
return true;
if(frequency < rhs.frequency)
return false;
if(frequency == rhs.frequency)
if(min > rhs.min)
return true;
return false;
}