{{ message }}

Instantly share code, notes, and snippets.

# kachayev/PairingHeap.py

Last active Oct 7, 2017
Pairing Heap implementation in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 ## ## 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 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 https://gist.github.com/alex1770/23292c136b1083c9adda06a8369bfb70 to see timings)