Last active
April 6, 2020 14:31
-
-
Save xpqz/c10b3009a68f9ffdc84c2fb09b44302a to your computer and use it in GitHub Desktop.
APL implementation of a leftist tree
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
⍝ APL implementation of a leftist tree. | |
⍝ | |
⍝ https://en.wikipedia.org/wiki/Leftist_tree | |
⍝ http://typeocaml.com/2015/03/12/heap-leftist-tree/ | |
⎕io←0 | |
Insert←{ ⍝ Insert item into leftist tree, returning the resulting tree | |
(tree item)←⍵ | |
1 item ⍬ ⍬ Merge tree | |
} | |
Pop←{ ⍝ Pop off smallest element from a leftist tree | |
0=≢⍵:⍬ | |
(v l r)←1↓⍵ ⍝ value left right | |
(l Merge r) v ⍝ Return the resulting tree and the value | |
} | |
Merge←{ ⍝ Merge two leftist trees, t1 and t2 | |
t1←⍺ ⋄ t2←⍵ | |
0=≢t1:t2 ⋄ 0=≢t2:t1 ⍝ If either is a leaf, return the other | |
(key1 left right)←1↓t1 ⋄ key2←1⌷t2 | |
key1>key2:t2∇t1 ⍝ Flip order to ensure smallest is root of merged | |
merged←right∇t2 ⍝ Merge rightwards | |
(⊃left)≥⊃merged:(1+⊃merged) key1 left merged ⍝ Right is shorter | |
(1+⊃left) key1 merged left ⍝ Left is shorter; make it the new right | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Priority queue/heap implemented as a Leftist Tree
A tree is a vector containing nodes of the type
for the example given in the ocaml implementation: http://typeocaml.com/2015/03/12/heap-leftist-tree/ :