-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathBinaryHeap.cs
96 lines (84 loc) · 2.5 KB
/
BinaryHeap.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
using System.Collections.Generic;
namespace Radar;
public class BinaryHeap<TKey, TValue>
{
private readonly List<KeyValuePair<TKey, TValue>> _storage = new List<KeyValuePair<TKey, TValue>>();
private void SieveUp(int startIndex)
{
var index = startIndex;
var nextIndex = (index - 1) / 2;
while (index != nextIndex)
{
if (Compare(index, nextIndex) < 0)
{
Swap(index, nextIndex);
}
else
{
return;
}
index = nextIndex;
nextIndex = (index - 1) / 2;
}
}
private void SieveDown(int startIndex)
{
var index = startIndex;
while (index * 2 + 1 < _storage.Count)
{
var child1 = index * 2 + 1;
var child2 = index * 2 + 2;
int nextIndex;
if (child2 < _storage.Count)
{
nextIndex = Compare(index, child1) > 0
? Compare(index, child2) > 0
? Compare(child1, child2) > 0
? child2
: child1
: child1
: Compare(index, child2) > 0
? child2
: index;
}
else
{
nextIndex = Compare(index, child1) > 0
? child1
: index;
}
if (nextIndex == index)
{
return;
}
Swap(index, nextIndex);
index = nextIndex;
}
}
private int Compare(int i1, int i2)
{
return Comparer<TKey>.Default.Compare(_storage[i1].Key, _storage[i2].Key);
}
private void Swap(int i1, int i2)
{
(_storage[i1], _storage[i2]) = (_storage[i2], _storage[i1]);
}
public void Add(TKey key, TValue value)
{
_storage.Add(new KeyValuePair<TKey, TValue>(key, value));
SieveUp(_storage.Count - 1);
}
public bool TryRemoveTop(out KeyValuePair<TKey, TValue> value)
{
if (_storage.Count == 0)
{
value = default;
return false;
}
value = _storage[0];
_storage[0] = _storage[^1];
_storage.RemoveAt(_storage.Count - 1);
SieveDown(0);
return true;
}
}