Search code examples
c#.netpriority-queue

How to change priority of an element contained in PriorityQueue in C#


Given an element contained in a .NET System.Collections.Generic.PriorityQueue, how does one change its priority value in-place? If this not possible, then should one Dequeue() the item, and Enqueue() it again with the new priority value? I don't see anything obvious in the documentation, but asking in case I've missed the relevant details.


Solution

  • PriorityQueue is a data structure which needs to store items in certain way to maintain complexity guarantees, so simple inplace replacement should not be possible in general case. You can use Enqueue/Dequeue approach but possibly recreating queue by using UnorderedItemsCollection property (processing in via LINQ and "replacing" needed item) and using EnqueueRange(IEnumerable<ValueTuple<TElement,TPriority>>) can be a faster approach (requires testing, especially with actual data).