Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# version of PriorityQueue for compare

I have the following code for Java and want to achieve same in C# . please suggest

    PriorityQueue<Integer> pQ= new PriorityQueue<Integer>((x,y)->Integer.compare(y, x));

I did convert Integer to int but does not helps.

.NET version < 6

like image 895
Dot Net Dev 19 Avatar asked Oct 23 '25 11:10

Dot Net Dev 19


2 Answers

If you are using .Net 6 and up you can use Comparer with PriorityQueue as:

For Increasing order:

PriorityQueue<int,int> pq = new PriorityQueue<int,int>(Comparer<int>.Create((a,b)=>a-b));

or for decreasing order:

PriorityQueue<int,int> pq = new PriorityQueue<int,int>(Comparer<int>.Create((a,b)=>b-a));
like image 200
ironman Avatar answered Oct 25 '25 02:10

ironman


If you are on .NET framework 6 (or newer) you just need:

var pQ = new PriorityQueue<int, int>();

If you add items you can give them a priority(2nd parameter):

pQ.Enqueue(1, 100);
pQ.Enqueue(2, 10);
// ...

or you have a complex logic that you want to reuse, then use a custom comparer:

public class MyFancyIntComparer : IComparer<int>
{
    public int Compare(int x, int y)
    {
        // replace following with a fancy logic
        return x.CompareTo(y);
    }
}

var pQ = new PriorityQueue<int, int>(new MyFancyIntComparer());

If you are on a lower version of the .NET framework you might use(copy&paste) these internal PriorityQueues: https://referencesource.microsoft.com/#q=priorityqueue

like image 44
Tim Schmelter Avatar answered Oct 25 '25 02:10

Tim Schmelter