Pairing Heap

Pairing heaps are multi-way tree structures, heap-ordered, and can be considered as simplified Fibonacci heaps. They were proposed by Fredman, Sedgewick, Sleator, and Tarjan in 1986 and attracted attention due to their unusually simple implementation combined with excellent asymptotic and practical properties.

How a pairing heap differs from a binary heap

The idea of the pairing operation

The secret of the pairing heap's efficiency lies in how subtrees are processed after the root is removed. The pairing method merges the subtrees in pairs: first the first and second trees in the list are merged, then the third and fourth, and so on, after which the result is merged into a single heap. This two-phase scheme ("first pairwise, then accumulate") yields amortized logarithmic complexity for insert and remove without the complex logic characteristic of the Fibonacci heap.

Although a rigorous proof of the amortized bounds of pairing heaps turned out to be non-trivial and remained an open question for a long time, in practice pairing heaps perform excellently and are often the fastest among the easily implementable ones.

Operations

All operations are expressed through the auxiliary merge of two heaps:

Complexity

Code

enum PairingHeap[+A]:

  import PairingHeap.*

  case Leaf
  private case Branch(min: A, subtrees: List[PairingHeap[A]])

  lazy val isEmpty: Boolean = this match
    case Leaf => true
    case _    => false

  def insert[B >: A: Ordering](x: B): PairingHeap[B] =
    merge(PairingHeap(x), this)

  def remove[B >: A: Ordering]: Option[PairingHeap[B]] = this match
    case Branch(_, subtrees) => Some(pairing(subtrees))
    case _                   => None

end PairingHeap

object PairingHeap:
  def empty[A]: PairingHeap[A] = Leaf

  def apply[A: Ordering](x: A): PairingHeap[A] =
    Branch(x, List.empty)

  private def merge[A: Ordering](
      x: PairingHeap[A],
      y: PairingHeap[A]
  ): PairingHeap[A] =
    (x, y) match
      case (_, Leaf) => x
      case (Leaf, _) => y
      case (Branch(x1, subs1), Branch(x2, subs2)) =>
        if x1 < x2 then
          Branch(x1, Branch(x2, subs2) :: subs1)
        else
          Branch(x2, Branch(x1, subs1) :: subs2)

  @tailrec
  private def pairing[A: Ordering](subtrees: List[PairingHeap[A]])
      : PairingHeap[A] =
    subtrees match
      case Nil              => Leaf
      case hd :: Nil        => hd
      case h1 :: h2 :: tail => pairing(merge(h1, h2) :: tail)

end PairingHeap

Understanding the Scala implementation


Links: