Priority Queue in C#
Comments available as RSS 2.0
A priority queue is like a standard queue, but instead of dequeuing items on a first-in-first-out basis, items are instead served by priority. There are lots of implementations of a priority queue, but none I could find which let the user re-order items. The following class functions just like a regular queue, but can also change the order of items in the queue by their index.
The queue is designed to be used with a ListView set to details mode, but could be adapted for use elsewhere. Using it with a ListView makes sense since the first item in the queue (the next to be executed) is always at index 0, and the indexing for a ListView also starts at 0.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Security.Permissions; using System.Runtime.Serialization; namespace Lime49.Utils { public class PriorityQueue { public ArrayList rawQueue; public delegate void QueueStructureChangedDelegate(); public event QueueStructureChangedDelegate QueueStructureChanged; public int Count { get { return rawQueue.Count; } } public PriorityQueue() { rawQueue = new ArrayList(); } public void Enqueue(object obj) { rawQueue.Add(obj); } public object Dequeue() { if(rawQueue.Count > 0) { //int idx = rawQueue.Count-1; object topItem = rawQueue[0]; rawQueue.RemoveAt(0); return topItem; } return null; } public object[] GetRange(int startIndex, int numItems) { object[] tempItems = new object[numItems - 1]; rawQueue.CopyTo(startIndex, tempItems, 0, numItems); rawQueue.RemoveRange(startIndex, numItems); return tempItems; } public object Peek() { return rawQueue[0]; } public void MoveToTop(int index) { object obj = rawQueue[index] as object; rawQueue.RemoveAt(index); rawQueue.Insert(0, obj); QueueStructureChanged(); } public void MoveUp(int index) { object obj = rawQueue[index] as object; rawQueue.RemoveAt(index); rawQueue.Insert(index - 1, obj); QueueStructureChanged(); } public void MoveDown(int index) { object obj = rawQueue[index] as object; rawQueue.RemoveAt(index); rawQueue.Insert(index + 1, obj); QueueStructureChanged(); } public void MoveToBottom(int index) { object obj = rawQueue[index] as object; rawQueue.RemoveAt(index); rawQueue.Add(obj); QueueStructureChanged(); } public void RemoveItem(int index) { rawQueue.RemoveAt(index); QueueStructureChanged(); } } }







Comments
Leave a Comment