C# priorityqueue with jagged array and customize sorting

72 Views Asked by At

I was recently reading the priorityqueue of C# and got confused by a writing. And would love to have some guidance.

The array int[][] need to be sorted is [[1,2],[2,4],[3,3],[3,2] ]

And the priorityqueue with comparer is:

PriorityQueue<int[], int[]> pq = new PriorityQueue<int[], int[]>(
    Comparer<int[]>.Create(
        (a, b) => a[1] == b[1]
            ? a[2] - b[2]
            : a[1] - b[1]
    )
);

I am pretty confused that it is used in that way later

pq.Enqueue(array[1],array[1]);

Can you tell me why it looks like that? Thank you.

2

There are 2 best solutions below

0
Progman On BEST ANSWER

The type of the element added to the priority queue and the type of the priority value can be different. Like a list of a complex type ConstructionOrder can be prioritize by the "cost" of the construction, which could be just an int value. That's why the PriorityQueue class has two generic types. It just happens to you, that the "element type" is the same as the "priority type", so the call

pq.Enqueue(array[1],array[1]);

means that the value array[1] (which is an int[] array) should be added to the queue and its priority is also the value of array[1]. And your PriorityQueue instance will sort the entries by your provided comparer.

0
AgentFire On

I'm having trouble with the concept of sorting the array using such a niche tool as PriorityQueue. Not only it does not guarantee the FIFO order between same-priority elements (proof), it simply is just not the right tool for the job.

My take on the simpliest solution would be to use LINQ to perform the sort. And since you've already presented your equality comparer, I can see it done in a something like this:

var comparer = Comparer<int[]>.Create(
    (a, b) => a[1] == b[1]
        ? a[2] - b[2]
        : a[1] - b[1]
)

var sortedArray = unsortedArray.OrderBy(x => x, comparer).ToArray();