Search code examples
c#priority-queue

C# priorityqueue with jagged array and customize sorting


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.


Solution

  • 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.