-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathClass3.cs
101 lines (89 loc) · 1.84 KB
/
Class3.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace File_Compression
{
public class PriorityQueue<T> where T : IComparable
{
int heapSize = -1;
List<HuffmanNode> nodes = new List<HuffmanNode>();
public int Size
{
get
{
return nodes.Count;
}
}
private void Swap(int i, int j)
{
var temp = nodes[i];
nodes[i] = nodes[j];
nodes[j] = temp;
}
private int LeftChild(int i)
{
return i * 2 + 1;
}
private int RightChild(int i)
{
return i * 2 + 2;
}
private void MinHeapify(int i)
{
int left = LeftChild(i);
int right = RightChild(i);
int smallest = i;
if (left <= heapSize && nodes[smallest].Frequency > nodes[left].Frequency)
smallest = left;
if (right <= heapSize && nodes[smallest].Frequency > nodes[right].Frequency)
smallest = right;
if (smallest != i)
{
Swap(smallest, i);
MinHeapify(smallest);
}
}
private void BuildHeap(int i)
{
while (i >= 0 && nodes[(i - 1) / 2].Frequency > nodes[i].Frequency)
{
Swap(i, (i - 1) / 2);
i = (i - 1) / 2;
}
}
public void Enqueue(HuffmanNode n)
{
nodes.Add(n);
heapSize++;
BuildHeap(heapSize);
}
public HuffmanNode Dequeue()
{
if (heapSize > -1)
{
var s = nodes[0];
nodes[0] = nodes[heapSize];
nodes.RemoveAt(heapSize);
heapSize--;
MinHeapify(0);
return s;
}
else
throw new Exception("Queue is empty");
}
public void Display()
{
Console.WriteLine("Symbols , Frequency");
for (int i = 0; i < nodes.Count; i++)
{
Console.WriteLine(nodes[i].Symbol + " , " + nodes[i].Frequency);
}
}
public bool isEmpty()
{
return (Size == 0) ? true : false;
}
}
}