Created
July 9, 2013 15:30
-
-
Save kachayev/5958312 to your computer and use it in GitHub Desktop.
Pairing heap data structure implementation in Erlang
This file contains hidden or 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 implementation | |
| %% more information on wiki: | |
| %% http://en.wikipedia.org/wiki/Pairing_heap | |
| %% pq :: {pq, heap(), int()} | |
| %% heap :: nil | {Item, [heap()]} | |
| %% ============================= | |
| %% API | |
| %% ============================= | |
| new() -> {pq, nil, 0}. | |
| min({pq, Heap, _}) -> heap_min(Heap). | |
| delete_min({pq, {X, Subs}, N}) -> | |
| {pq, pairs(Subs), N-1}. | |
| insert(X, {pq, Heap, N}) -> | |
| {pq, meld(Heap,{X, []}), N+1}. | |
| merge({pq, X, M}, {pq, Y, N}) -> | |
| {pq, meld(X,Y), M+N}. | |
| size({pq, _, N}) -> N. | |
| %% heapsort! | |
| to_list({pq, nil, 0}) -> []; | |
| to_list(Q) -> [min(Q) | to_list(delete_min(Q))]. | |
| %% ============================= | |
| %% implementation details | |
| %% ============================= | |
| heap_min({X, _}) -> X. | |
| meld(Q, nil) -> Q; | |
| meld(nil, Q) -> Q; | |
| meld({X, SubL}, R = {Y, _}) when X < Y -> | |
| {X, [R|SubL]}; | |
| meld(L, {Y, SubR}) -> | |
| {Y, [L|SubR]}. | |
| pairs([]) -> nil; | |
| pairs([Q]) -> Q; | |
| pairs([Q1, Q2 | Q]) -> pairs([meld(Q1, Q2) | Q]). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think the last line is wrong? According to wikipedia it should be:
pairs([Q1, Q2 | Q]) -> meld(meld(Q1, Q2), pairs(Q)).