-
Notifications
You must be signed in to change notification settings - Fork 10
/
PriorityQueue.cs
388 lines (346 loc) · 12.9 KB
/
PriorityQueue.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/*
* PriorityQueue.cs - A simple binary heap priority queue generic collection.
*
* Copyright © 2007, Jim Mischel.
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace gep
{
/// <summary>
/// Represents an item stored in a priority queue.
/// </summary>
/// <typeparam name="TValue">The type of object in the queue.</typeparam>
/// <typeparam name="int">The type of the priority field.</typeparam>
struct PriorityQueueItem<TValue>
{
private TValue value;
private int priority;
public PriorityQueueItem(TValue val, int pri)
{
this.value = val;
this.priority = pri;
}
/// <summary>
/// Gets the value of this PriorityQueueItem.
/// </summary>
public TValue Value
{
get { return value; }
}
/// <summary>
/// Gets the priority associated with this PriorityQueueItem.
/// </summary>
public int Priority
{
get { return priority; }
}
}
/// <summary>
/// Represents a binary heap priority queue.
/// </summary>
/// <typeparam name="TValue">The type of object in the queue.</typeparam>
/// <typeparam name="int">The type of the priority field.</typeparam>
[Serializable]
[ComVisible(false)]
class PriorityQueue<TValue> : ICollection,
IEnumerable<PriorityQueueItem<TValue>>
{
private PriorityQueueItem<TValue>[] items;
private const Int32 DefaultCapacity = 16;
private Int32 capacity;
private Int32 numItems;
//private Comparison<int> compareFunc;
/// <summary>
/// Initializes a new instance of the PriorityQueue class that is empty,
/// has the default initial capacity, and uses the default IComparer.
/// </summary>
public PriorityQueue()
: this(DefaultCapacity)
{
}
/// <summary>
/// Initializes a new instance of the PriorityQueue class that is empty,
/// has the specified initial capacity, and uses the default IComparer.
/// </summary>
/// <param name="initialCapacity">Desired initial capacity.</param>
public PriorityQueue(Int32 initialCapacity)
{
Init(initialCapacity);
}
// Initializes the queue
private void Init(int initialCapacity)
{
numItems = 0;
SetCapacity(initialCapacity);
}
/// <summary>
/// Gets the number of items that are currently in the queue.
/// </summary>
public int Count
{
get { return numItems; }
}
/// <summary>
/// Gets or sets the queue's capacity.
/// </summary>
public int Capacity
{
get { return items.Length; }
set { SetCapacity(value); }
}
// Set the queue's capacity.
private void SetCapacity(int newCapacity)
{
int newCap = newCapacity;
if (newCap < DefaultCapacity)
newCap = DefaultCapacity;
// throw exception if newCapacity < numItems
if (newCap < numItems)
throw new ArgumentOutOfRangeException("newCapacity", "New capacity is less than Count");
this.capacity = newCap;
if (items == null)
{
// Initial allocation.
items = new PriorityQueueItem<TValue>[newCap];
return;
}
// Resize the array.
Array.Resize(ref items, newCap);
}
/// <summary>
/// Adds an object to the queue, in order by priority.
/// </summary>
/// <param name="value">The object to be added.</param>
/// <param name="priority">Priority of the object to be added.</param>
public void Enqueue(TValue value, int priority)
{
if (numItems == capacity)
{
// need to increase capacity
// grow by 50 percent
SetCapacity((3*Capacity)/2);
}
// Create the new item
PriorityQueueItem<TValue> newItem =
new PriorityQueueItem<TValue>(value, priority);
int i = numItems;
++numItems;
// and insert it into the heap.
while ((i > 0) && (items[i/2].Priority > newItem.Priority))
{
items[i] = items[i/2];
i /= 2;
}
items[i] = newItem;
}
// Remove a node at a particular position in the queue.
private PriorityQueueItem<TValue> RemoveAt (Int32 index)
{
// remove an item from the heap
PriorityQueueItem<TValue> o = items[index];
PriorityQueueItem<TValue> tmp = items[numItems-1];
items[--numItems] = default(PriorityQueueItem<TValue>) ;
if (numItems > 0)
{
int i = index;
int j = i+1;
while (i < Count/2)
{
if ((j < Count-1) && (items[j].Priority > items[j+1].Priority))
{
j++;
}
if (items[j].Priority >= tmp.Priority)
{
break;
}
items[i] = items[j];
i = j;
j *= 2;
}
items[i] = tmp;
}
return o;
}
/// <summary>
/// Removes and returns the item with the highest priority from the queue.
/// </summary>
/// <returns>The object that is removed from the beginning of the queue.</returns>
public PriorityQueueItem<TValue> Dequeue()
{
if (Count == 0)
throw new InvalidOperationException("The queue is empty");
return RemoveAt(0);
}
/// <summary>
/// Removes the item with the specified value from the queue.
/// The passed equality comparison is used.
/// </summary>
/// <param name="item">The item to be removed.</param>
/// <param name="comp">An object that implements the IEqualityComparer interface
/// for the type of item in the collection.</param>
public void Remove(TValue item, IEqualityComparer comparer)
{
// need to find the PriorityQueueItem that has the Data value of o
for (int index = 0; index < numItems; ++index)
{
if (comparer.Equals(item, items[index].Value))
{
RemoveAt(index);
return;
}
}
throw new ApplicationException("The specified itemm is not in the queue.");
}
/// <summary>
/// Removes the item with the specified value from the queue.
/// The default type comparison function is used.
/// </summary>
/// <param name="item">The item to be removed.</param>
public void Remove(TValue item)
{
Remove(item, EqualityComparer<TValue>.Default);
}
/// <summary>
/// Returns the object at the beginning of the priority queue without removing it.
/// </summary>
/// <returns>The object at the beginning of the queue.</returns>
public PriorityQueueItem<TValue> Peek()
{
if (Count == 0)
throw new InvalidOperationException("The queue is empty");
return items[0];
}
/// <summary>
/// Removes all objects from the queue.
/// </summary>
public void Clear()
{
numItems = 0;
TrimExcess();
}
/// <summary>
/// Sets the capacity to the actual number of elements in the Queue,
/// if that number is less than 90 percent of current capacity.
/// </summary>
public void TrimExcess()
{
if (numItems < (0.9 * capacity))
SetCapacity(numItems);
}
/// <summary>
/// Determines whether an element is in the queue.
/// </summary>
/// <param name="o">The object to locate in the queue.</param>
/// <returns>True if item found in the queue. False otherwise.</returns>
public bool Contains(TValue item)
{
foreach (PriorityQueueItem<TValue> qItem in items)
{
if (qItem.Value.Equals(item))
return true;
}
return false;
}
/// <summary>
/// Copies the elements of the ICollection to an Array, starting at a particular Array index.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination of the elements copied from ICollection.
/// The Array must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in array at which copying begins.</param>
public void CopyTo(PriorityQueueItem<TValue>[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex", "arrayIndex is less than 0.");
if (array.Rank > 1)
throw new ArgumentException("array is multidimensional.");
if (arrayIndex >= array.Length)
throw new ArgumentException("arrayIndex is equal to or greater than the length of the array.");
if (numItems > (array.Length - arrayIndex))
throw new ArgumentException("The number of elements in the source ICollection is greater than the available space from arrayIndex to the end of the destination array.");
Array.Copy(items, 0, array, arrayIndex, numItems);
}
/// <summary>
/// Copies the queue elements to a new array.
/// </summary>
/// <returns>A new array containing elements copied from the Queue.</returns>
public PriorityQueueItem<TValue>[] ToArray()
{
PriorityQueueItem<TValue>[] newItems =
new PriorityQueueItem<TValue>[numItems];
Array.Copy(items, newItems, numItems);
return newItems;
}
#region ICollection Members
/// <summary>
/// Copies the elements of the ICollection to an Array, starting at a particular Array index.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination of the elements copied from ICollection.
/// The Array must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in array at which copying begins.</param>
void ICollection.CopyTo(Array array, int index)
{
this.CopyTo((PriorityQueueItem<TValue>[])array, index);
}
/// <summary>
/// Gets a value indicating whether access to the ICollection is synchronized (thread safe).
/// </summary>
bool ICollection.IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the ICollection.
/// </summary>
object ICollection.SyncRoot
{
get { return items.SyncRoot; }
}
#endregion
#region IEnumerable<PriorityQueueItem<TValue,int>> Members
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>An IEnumerator that can be used to iterate through the collection.</returns>
public IEnumerator<PriorityQueueItem<TValue>> GetEnumerator()
{
for (int i = 0; i < numItems; i++)
{
yield return items[i];
}
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>An IEnumerator that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}