Skip to content

Instantly share code, notes, and snippets.

Last active Oct 7, 2017
What would you like to do?
Pairing Heap implementation in Python
## Pairing heap data structure
## More information on wiki:
## Data types
## Heap :: (Elem | None, Subs)
## Subs :: None | (Heap, Subs)
def heap(el=None):
return (el, None)
def insert(h, el):
return meld(h, heap(el))
def extract((_, subs)):
return pairing(subs)
def min((el, subs)):
return el
def meld((el1, subs1), (el2, subs2)):
if el1 is None: return (el2, subs2)
if el2 is None: return (el1, subs1)
if el1 < el2:
return (el1, ((el2, subs2), subs1))
return (el2, ((el1, subs1), subs2))
def pairing(qs):
if qs is None: return heap()
(q1,tail) = qs
if tail is None: return q1
(q2, tail) = tail
return pairing((meld(q1,q2), tail))
if __name__ == "__main__":
print "=== Pairing heap ==="
from random import randint
ph = heap()
for _ in xrange(20):
ph = insert(ph, randint(1,20))
# emulate heapsort
while 1:
if min(ph) is None: break
print "->", min(ph)
ph = extract(ph)
Copy link

alex1770 commented May 25, 2017

Nice clean version, but the last line of the pairing function is not quite right. It needs to be
return meld(meld(q1,q2), pairing(tail))
The current version has quadratic time complexity.
(See to see timings)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment