Czoko_Smieciarka/Trunk/MonoGameView/Algorithms/PriorityQueue.cs

52 lines
1.3 KiB
C#
Raw Normal View History

2019-05-14 21:42:05 +02:00
using System.Collections.Generic;
public class PriorityQueue<T>
{
// The items and priorities.
List<T> Values = new List<T>();
List<int> Priorities = new List<int>();
// Return the number of items in the queue.
public int NumItems
{
get
{
return Values.Count;
}
}
// Add an item to the queue.
public void AddAt(int index,T new_value, int new_priority)
{
Values.Insert(index, new_value);
Priorities.Insert(index, new_priority);
}
public void Enqueue(T new_value, int new_priority)
{
var index = 0;
foreach (var item in Priorities)
{
if (item < new_priority) index++;
else break;
}
Values.Insert(index,new_value);
Priorities.Insert(index,new_priority);
}
// Remove the item with the largest priority from the queue.
public KeyValuePair<T,int> Dequeue()
{
// Find the hightest priority.
var best_index = 0;
// Return the corresponding item.
var top_value = Values[best_index];
var top_priotiy = Priorities[best_index];
// Remove the item from the lists.
Values.RemoveAt(best_index);
Priorities.RemoveAt(best_index);
return new KeyValuePair<T,int>(top_value,top_priotiy);
}
}