Skip to content

Instantly share code, notes, and snippets.

@kachayev
Last active October 7, 2017 13:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kachayev/5990757 to your computer and use it in GitHub Desktop.
Save kachayev/5990757 to your computer and use it in GitHub Desktop.
Pairing Heap implementation in Python
##
## Pairing heap data structure
## More information on wiki:
## http://en.wikipedia.org/wiki/Pairing_heap
##
## 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))
else:
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)
@alex1770
Copy link

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 https://gist.github.com/alex1770/23292c136b1083c9adda06a8369bfb70 to see timings)

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