2 ! Copyright 2007 Ryan Murphy
3 ! See http://factorcode.org/license.txt for BSD license.
5 USING: kernel math sequences ;
8 : [comp] ( elt elt -- ? ) <=> 0 > ;
10 : <heap> ( -- heap ) V{ } clone ;
12 : left ( index -- index ) ! left child
15 : leftv ( heap index -- value )
18 : right ( index -- index ) ! right child
21 : rightv ( heap index -- value )
24 : l-oob ( i heap -- ? ) swap left swap length >= ;
25 : r-oob ( i heap -- ? ) swap right swap length >= ;
27 : up ( index -- index ) ! parent node
30 : upv ( heap index -- value ) ! parent's value
33 : lasti ( seq -- index ) length 1 - ;
35 : swapup ( heap index -- ) dup up rot exchange ;
37 : (farchild) ( heap index -- index ) tuck 2dup leftv -rot rightv [comp] [ right ] [ left ] if ;
39 : farchild ( heap index -- index ) dup right pick length >= [ nip left ] [ (farchild) ] if ;
41 : farchildv ( heap index -- value ) dupd farchild swap nth ;
43 : swapdown ( heap index -- ) 2dup farchild rot exchange ;
46 dup dup lasti upv over peek [comp]
47 [ dup lasti 2dup swapup up 1 + head-slice upheap ] [ drop ] if ;
52 : add-many ( seq heap -- )
53 swap [ swap add ] each-with ;
57 : (downheap2) ( i heap -- )
59 2dup swap farchild dup pick nth 2swap
62 [ r> r> tuck swap swapdown (downheap) ] [ drop r> r> 2drop ] if ;
64 : (downheap) ( i heap -- )
65 over left over length >= [ 2drop ] [ (downheap2) ] if ;
67 : downheap ( heap -- )
71 dup peek 0 pick set-nth dup pop* downheap ;
73 : gbump ( heap -- first )