Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 591
user3335040 Avatar asked Nov 25 '14 05:11

user3335040


People also ask

How to build max heap from min heap?

The idea is, simply build Max Heap without caring about the input. Start from the bottom-most and rightmost internal node of Min-Heap and heapify all internal modes in the bottom-up way to build the Max heap. Call the Heapify function from the rightmost internal node of Min-Heap Heapify all internal nodes in the bottom-up way to build max heap

What is Min Heapify in Java?

1. min-heapify function This function makes a node and all its descendants (child nodes and their child) follow the heap property. It rearranges the nodes by swapping them so as to make the given heap the smallest node in its subtree, following the heap property.

What is a min-heap data structure?

The min-heap data structure is generally used to represent a priority queue. How are heaps represented in arrays? We have already seen how a heap is represented in memory in the form of an array, just a quick reminder that:

What is the difference between min-heap and max-heap in Java?

This is regardless of the data stored in the heap. There are two types of heaps: Min-heap and Max-heap. A min-heap is used to access the minimum element in the heap whereas the Max-heap is used when accessing the maximum element in the heap.


2 Answers

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
like image 126
Marth Avatar answered Sep 21 '22 07:09

Marth


Update August 2016: you can consider the proposal chrisokasaki/scads/scala/heapTraits.scala from Chris Okasaki (chrisokasaki).

That proposal illustrates the "not-so-easy" part of an Heap:

Proof of concept for typesafe heaps with a merge operation.
Here, "typesafe" means that the interface will never allow different orderings to be mixed within the same heap.
In particular,

  • when adding an element to an existing heap, that insertion cannot involve an ordering different from the one used to create the existing heap, and
  • when merging two existing heaps, the heaps are guaranteed to have been created with the same ordering.

See its design.

val h1 = LeftistHeap.Min.empty[Int] // an empty min-heap of integers
like image 39
VonC Avatar answered Sep 22 '22 07:09

VonC