Skip to content

Instantly share code, notes, and snippets.

@KamilaBorowska
Last active December 11, 2015 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KamilaBorowska/4577858 to your computer and use it in GitHub Desktop.
Save KamilaBorowska/4577858 to your computer and use it in GitHub Desktop.
The buggy code
multi binary-search ($x, @array --> Int) {
binary_search $x, @array, 0, end @array;
}
multi binary-search ($x, @array, Int $low, Int $high --> Int) {
return Int unless $low before $high;
my Int $middle = ($low + $high) div 2;
# In Perl 6, cmp is DWIM comparison, unlike Perl 5
given $x cmp @array[$middle] {
when Increase { binary_search $x, @array, $low, $middle - 1 }
when Decrease { binary_search $x, @array, $middle + 1, $high }
when Same { $middle }
}
}
say binary-search 42, [1, 5, 7, 23, 33, 37, 39, 41, 42, 45, 56, 72];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment