Search code examples
scaladata-structurespriority-queuemin-heap

What is the easiest and most efficient way to make a min heap in Scala?


val maxHeap = scala.collection.mutable.PriorityQueue[Int] //Gives MaxHeap

What is the most concise and efficient way to use Ordering to turn a PriorityQueue into a minHeap?


Solution

  • You'll have to define your own Ordering :

    scala> object MinOrder extends Ordering[Int] {
             def compare(x:Int, y:Int) = y compare x
           }
    defined object MinOrder
    

    Then use that when creating the heap :

    scala> val minHeap = scala.collection.mutable.PriorityQueue.empty(MinOrder)
    minHeap: scala.collection.mutable.PriorityQueue[Int] = PriorityQueue()
    
    scala> minHeap.ord
    res1: Ordering[Int] = MinOrder$@158ac84e