-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMinBinaryHeapBasedPriorityQueue.cs
More file actions
117 lines (99 loc) · 2.72 KB
/
MinBinaryHeapBasedPriorityQueue.cs
File metadata and controls
117 lines (99 loc) · 2.72 KB
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
107
108
109
110
111
112
113
114
115
116
117
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace AlgorithmsAndDataStructures.DataStructures.BinaryHeaps;
#pragma warning disable CA1010 // Collections should implement generic interface
#pragma warning disable CA1710 // Identifiers should have correct suffix
public class MinBinaryHeapBasedPriorityQueue<T> : IProducerConsumerCollection<T> where T : IComparable<T>
#pragma warning restore CA1710 // Identifiers should have correct suffix
#pragma warning restore CA1010 // Collections should implement generic interface
{
private readonly MinBinaryHeap<T> heap;
public MinBinaryHeapBasedPriorityQueue(int initialCapacity = 8)
{
heap = new MinBinaryHeap<T>(initialCapacity);
}
public int Count
{
get
{
lock (SyncRoot)
{
return heap?.GetHeap()?.Length ?? 0;
}
}
}
public bool IsSynchronized => true;
public object SyncRoot { get; } = new();
public void CopyTo(T[] array, int index)
{
throw new NotImplementedException();
}
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
public IEnumerator<T> GetEnumerator()
{
IEnumerator<T> result;
lock (SyncRoot)
{
var heapCopy = heap.GetHeap();
Array.Sort(heapCopy);
#pragma warning disable HAA0401 // Possible allocation of reference type enumerator
result = heapCopy.AsEnumerable().GetEnumerator();
#pragma warning restore HAA0401 // Possible allocation of reference type enumerator
}
return result;
}
public T[] ToArray()
{
var heapCopy = heap.GetHeap();
Array.Sort(heapCopy);
return heapCopy;
}
public bool TryAdd(T item)
{
try
{
lock (SyncRoot)
{
heap.Insert(item);
}
}
// Probably not the best idea to control execution like this.
catch (ArgumentException)
{
return false;
}
return true;
}
public bool TryTake(out T item)
{
try
{
lock (SyncRoot)
{
item = heap.GetTop();
}
}
// Probably not the best idea to control execution like this.
catch (ArgumentException)
{
item = default;
return false;
}
return true;
}
IEnumerator IEnumerable.GetEnumerator()
{
IEnumerator result;
lock (SyncRoot)
{
result = heap.GetHeap().GetEnumerator();
}
return result;
}
}