use My::Bintree; my $T = My::Bintree->new(3, sub { return $_[0] <=> $_[1] }); $T->add(5); $T->add(2); $T->add(8); $T->add(8); $T->add(8); print "maxi: ".join(",",$T->maxi())."\nmini: ".join(",",$T->mini())."\n"; print "searched for number 8: ".join(",", $T->search(8))."\n"; # maxi: 8 8 8 # mini: 2 # searched for number 8: 8,8,8 # or add complex data, e.g. (x,y) points and compare their distance from origin $T = My::Bintree->new( # a first point: [1,2], # the comparator: sub { return $_[0]->[0]**2 + $_[0]->[1]**2 <=> $_[1]->[0]**2 + $_[1]->[1]**2 } ); $T->add([3,8]); $T->add([5,5]); $T->add([3,4]); $T->add([3,2]); $T->add([3,6]); $T->add([2,3]); $T->add([3,2]); $T->add([2,1]); print "furthest point(s): ".join(',', map { '(x: '.$_->[0].', y: '.$_->[1].')' } $T->maxi())."\n"; print "nearest point(s): ".join(',', map { '(x: '.$_->[0].', y: '.$_->[1].')' } $T->mini())."\n"; print "searched for points with same distance from origin as point (2,3): ".join(',', map { '(x: '.$_->[0].', y: '.$_->[1].')' } $T->search([2,3]))."\n"; # furthest point(s): (x: 3, y: 8) # nearest point(s): (x: 1, y: 2),(x: 2, y: 1) # searched for points with same distance from origin as point (2,3): (x: 3, y: 2),(x: 2, y: 3),(x: 3, y: 2) # here is how you find the max index (and value) of an array # even if there are several max/min values my @arr = (3,4,5,100,4,5,100,100, 0, 1, 2); # the comparator must return -1 if 1st arg < 2nd arg!!! (re: edit above) $T = My::Bintree->new([0, shift @arr], sub { $_[0]->[1] <=> $_[1]->[1] }); $T->add([$_,$arr[$_]]) for 0..$#arr; print "max: ".join(',', map { '(index: '.$_->[0].', value: '.$_->[1].')' } $T->maxi())."\n"; print "min: ".join(',', map { '(index: '.$_->[0].', value: '.$_->[1].')' } $T->mini())."\n"; print "searched for value of 5: ".join(',', map { '(index: '.$_->[0].', value: '.$_->[1].')' } $T->search([undef,5]))."\n"; # max: (index: 2, value: 100),(index: 5, value: 100),(index: 6, value: 100) # min: (index: 7, value: 0) # searched for value of 5: (index: 1, value: 5),(index: 4, value: 5)