Created
March 16, 2019 16:48
-
-
Save tomcha/426a8dee9ffdd90a848625cd6a9810cb to your computer and use it in GitHub Desktop.
binary_search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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