Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.