Home > Back-end >  How to change priority of an element contained in PriorityQueue in C#
How to change priority of an element contained in PriorityQueue in C#

Time:01-08

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.

CodePudding user response:

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 (needs testing, especially with actual data) 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.

CodePudding user response:

The PriorityQueue<TElement,TPriority> collection is not updateable. Supporting updates would require maintaining more state, and the enqueue/dequeue operations would become slower, so Microsoft opted for releasing a non-updateable version. There is a proposal on GitHub for adding the update functionality, that you could support by upvoting the proposal:

  • Related