0

C# has the PriorityQueue<TElement,TPriority> Class in .NET 6. By default, this PriorityQueue is a Min Heap.

Now, I want to use PriorityQueue to implement Max Heap by adding my own Compare() method. But, maybe, due to some bugs, it still works as a Min Heap.

Here is my code:

using System;
using System.Collections.Generic;

class Max_Heap : IComparer<int>{
    
     public int Compare(int first, int second)
     {
        if (first == second) 
        {
            return 0;
        }
        else if (first > second) 
        {
            return -1;
        }
        else 
        {
            return 1;
        }
    }
    
  static void Main() {
    Console.WriteLine("Hello World. Here is my Max Heap:");

    PriorityQueue<string, int> queue = new PriorityQueue<string, int>();

    queue.Enqueue("Item A", 0);
    queue.Enqueue("Item B", 60);
    queue.Enqueue("Item C", 45);
    queue.Enqueue("Item D", 1);

    while (queue.TryDequeue(out string item, out int priority))
    {
       Console.WriteLine($"Popped Item : {item}. Priority Was : {priority}");
    }

  }
}

Please tell me how I can fix this code to make it behave as a Max Heap.

==============================

Updated: I figured out where the bug is. When I instantiate the PriorityQueue, I must also instantiate an instance of the class that contains the Compare() method and pass it to the constructor of the PriorityQueue as follow:

PriorityQueue<string, int> queue = new PriorityQueue<string, int>(new Max_Heap());

This new code will work as I have tested it.

Job_September_2020
  • 858
  • 2
  • 10
  • 25

0 Answers0