binary_search.pl 738 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 10 July 2019
  4. # https://github.com/trizen
  5. # The binary search algorithm.
  6. # See also:
  7. # https://en.wikipedia.org/wiki/Binary_search_algorithm
  8. use 5.020;
  9. use strict;
  10. use warnings;
  11. use experimental qw(signatures);
  12. sub bsearch ($left, $right, $callback) {
  13. while ($left <= $right) {
  14. my $mid = int(($left + $right) / 2);
  15. my $cmp = $callback->($mid) || return $mid;
  16. if ($cmp > 0) {
  17. $right = $mid - 1;
  18. }
  19. else {
  20. $left = $mid + 1;
  21. }
  22. }
  23. return undef;
  24. }
  25. say bsearch(0, 202, sub ($x) { $x * $x <=> 49 }); #=> 7 (7*7 = 49)
  26. say bsearch(3, 1000, sub ($x) { $x**$x <=> 3125 }); #=> 5 (5**5 = 3125)