-
Notifications
You must be signed in to change notification settings - Fork 0
/
Heap.cs
100 lines (83 loc) · 2.19 KB
/
Heap.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
namespace BinaryHeap;
public enum HeapType
{
Min,
Max
}
public class Heap<T> where T : IComparable<T>
{
private List<T> heap;
private HeapType heapType;
public Heap() : this(HeapType.Max)
{
}
public Heap(HeapType heapType)
{
heap = new List<T>();
this.heapType = heapType;
}
public bool IsEmpty()
{
return this.heap.Count == 0;
}
public void Push(T item)
{
var oldLength = heap.Count;
heap.Add(item);
SiftUp(oldLength);
}
public T Pop()
{
if (this.IsEmpty())
{
return default;
}
var max = heap[0];
var last = heap[heap.Count - 1];
heap.RemoveAt(heap.Count - 1);
if (heap.Count > 0)
{
heap[0] = last;
SiftDown(0);
}
return max;
}
private void SiftUp(int index)
{
if (index == 0)
{
return;
}
int parentIndex = (index - 1) / 2;
Func<T, T, bool> shouldSwap = (heapType == HeapType.Max) ?
new Func<T, T, bool>((a, b) => a.CompareTo(b) > 0) :
new Func<T, T, bool>((a, b) => a.CompareTo(b) < 0);
if (shouldSwap(heap[index], heap[parentIndex]))
{
(heap[index], heap[parentIndex]) = (heap[parentIndex], heap[index]);
SiftUp(parentIndex);
}
}
private void SiftDown(int index)
{
int leftChildIndex = index * 2 + 1;
int rightChildIndex = index * 2 + 2;
if (leftChildIndex >= heap.Count)
{
return;
}
Func<T, T, bool> comparison = (heapType == HeapType.Max) ?
new Func<T, T, bool>((a, b) => a.CompareTo(b) > 0) :
new Func<T, T, bool>((a, b) => a.CompareTo(b) < 0);
int childIndex = leftChildIndex;
if (rightChildIndex < heap.Count && comparison(heap[rightChildIndex], heap[leftChildIndex]))
{
childIndex = rightChildIndex;
}
if (comparison(heap[childIndex], heap[index]))
{
(heap[index], heap[childIndex]) = (heap[childIndex], heap[index]);
SiftDown(childIndex);
}
}
}