-
-
Save masak/abdbddcb25983fbd8935 to your computer and use it in GitHub Desktop.
My binary search
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
sub search(@values, &break_decision) is export { | |
my $min_ix_excl = -1; | |
my $max_ix_incl = @values.elems - 1; | |
while $min_ix_excl < $max_ix_incl { | |
my $middle_ix = ($min_ix_excl + $max_ix_incl + 1) div 2; | |
if break_decision(@values[$middle_ix]) == Keep { # should look higher | |
$min_ix_excl = $middle_ix; | |
} | |
else { # == Break # should look here or lower | |
$max_ix_incl = $middle_ix; | |
} | |
return @values[$max_ix_incl] | |
if $max_ix_incl == $min_ix_excl + 1; | |
} | |
fail; | |
} |
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
{ | |
my @values = 5, 10, 15, 20, 25, 30, 35, 40; | |
my &decision = -> $v { $v > 12 ?? Break !! Keep }; | |
is search(@values, &decision), 15, "it finds the right value"; | |
} | |
{ | |
my @values = 5, 10, 15, 20, 25, 30, 35, 40; | |
my &decision = -> $v { $v > 3 ?? Break !! Keep }; | |
is search(@values, &decision), 5, "it finds the value at one endpoint"; | |
} | |
{ | |
my @values = 5, 10, 15, 20, 25, 30, 35, 40; | |
my &decision = -> $v { $v > 37 ?? Break !! Keep }; | |
is search(@values, &decision), 40, "it finds the value at the other endpoint"; | |
} | |
{ | |
my @values = 5; | |
my &decision = -> $v { $v > 3 ?? Break !! Keep }; | |
is search(@values, &decision), 5, "it finds the only value, when it's valid"; | |
} | |
{ | |
my @values = 5; | |
my &decision = -> $v { $v > 7 ?? Break !! Keep }; | |
ok !search(@values, &decision).defined, "it fails when the only value isn't valid"; | |
} | |
{ | |
my @values; | |
my &decision = -> $v { $v > 13 ?? Break !! Keep }; | |
ok !search(@values, &decision).defined, "it fails when there are no values in the list"; | |
} | |
done; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment