Skip to content

Instantly share code, notes, and snippets.

@tomcha
Created March 16, 2019 16:48
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 tomcha/426a8dee9ffdd90a848625cd6a9810cb to your computer and use it in GitHub Desktop.
Save tomcha/426a8dee9ffdd90a848625cd6a9810cb to your computer and use it in GitHub Desktop.
binary_search
#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
use DDP { deparse => 1 };
my @seeds;
for (1..100){
push(@seeds, int(rand(100)));
}
my %hash;
my @array = grep{!$hash{$_}++}@seeds;
@array = sort {$a <=> $b} @array;
p @array;
my ($s, $e) = (0, scalar @array - 1);
my $target = 23;
my $size = @array;
my $result;
my $c = 1;
while ($size > 1){
say "loop: $c,size: $size, s: $s, e: $e";
my $i = int($size / 2);
if ($array[$s + $i] == $target){
$result = $s + $i;
last;
} elsif ($array[$s + $i] > $target){
$e = $s + $i;
} else{
$s = $s + $i;
}
$size = $e - $s;
$c++;
}
if ($result){
say "result : $result";
} else {
say "$target not incluide.";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment