binary_search_le.pl 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 10 July 2019
  4. # https://github.com/trizen
  5. # The binary search algorithm: "less than or equal to" variation.
  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_le ($left, $right, $callback) {
  13. my ($mid, $cmp);
  14. for (; ;) {
  15. $mid = int(($left + $right) / 2);
  16. $cmp = $callback->($mid) || return $mid;
  17. if ($cmp < 0) {
  18. $left = $mid + 1;
  19. $left > $right and last;
  20. }
  21. else {
  22. $right = $mid - 1;
  23. if ($left > $right) {
  24. $mid -= 1;
  25. last;
  26. }
  27. }
  28. }
  29. return $mid;
  30. }
  31. say bsearch_le(0, 202, sub ($x) { $x * $x <=> 49 }); #=> 7 (7*7 = 49)
  32. say bsearch_le(3, 1000, sub ($x) { $x**$x <=> 3125 }); #=> 5 (5**5 = 3125)
  33. say bsearch_le(1, 1e6, sub ($x) { exp($x) <=> 1e+9 }); #=> 20 (exp( 20) <= 1e+9)
  34. say bsearch_le(-1e6, 1e6, sub ($x) { exp($x) <=> 1e-9 }); #=> -21 (exp(-21) <= 1e-9)