# Meldable Priority Queue Operations

Data Structure AlgorithmsAnalysis of AlgorithmsAlgorithms

The randomized meldable heap(also called as Meldable Priority Queue) supports a number of common operations. These are known as insertion, deletion, and a searching operation, findMin. The insertion and deletion operations are implemented in terms of an additional operation specific to the meldable heap, Meld(A1, A2).

## Meld

The basic target of the meld (also called as merge) operation is to take two heaps (by taking each heaps root nodes), A1 and A2, and merges them, returning a single heap node as a result. This heap node is the root node of a heap containing all elements from the two subtrees rooted at A1 and A2.

An excellent feature of this meld operation is that it can be defined recursively. If either heaps are associated with null value, then the merge is accomplished with an empty set and the method returns the root node of the non-empty heap. If both A1 and A2 are not nil, check if A1 > A2. If it is, swap the two. It is therefore ensured that A1 < A2 and that the root node of the merged heap will contain A1. We then recursively merge A2 with A1.left or A1.right. This step is where the randomization comes in as this decision of which side to merge with is decided by a coin toss.

function Meld(Node A1, Node A2)
if A1 is nil => return A2
if A2 is nil => return A1
if A1 > A2 => swap A1 and A2
if coin_toss is 0 => A1.left = Meld(A1.left, A2)
else A1.right = Meld(A1.right, A2)
return A1

## Insert

With the meld operation complete, inserting into the meldable heap is so simple. First, a new node, a, is created containing the value p. This new node is then simply merged with the heaps root node.

function Insert(p)
Node a = new Node
a.p = p
root = Meld(a, root)
root.parent = nil
increment node count

## Remove

Same as easy to the insert operation, Remove() implements the Meld operation to eliminate the root node from the heap. This is accomplished by simply melding the two children of the root node and making the returned node as the new root.

function Remove()
rootNode = Meld(rootNode.left, rootNode.right)
if rootNode is not nil => rootNode.parent = nil
decrement node count

## FindMin

Possibly the simplest operation for the randomized meldable heap, FindMin() simply returns the present element stored in the heap's root node.