Last active
February 27, 2017 15:50
-
-
Save western/e52acd80af18355a5be676de51a5e1be to your computer and use it in GitHub Desktop.
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
package AndrewPFindIndex; | |
use strict; | |
use warnings; | |
use Data::Dumper; | |
# sorted array | |
my $arr = [1,2,3,5,95,97,100]; | |
sub new{ | |
my $c = shift; | |
my $class = ref $c || $c; | |
my %arg = @_; | |
my $o = {}; | |
bless $o, $class; | |
return $o; | |
} | |
sub find{ | |
my $o = shift; | |
my ($word) = @_; | |
my $low = 0; | |
my $high = @$arr - 1; | |
my $step = 0; | |
while ( $low <= $high ){ | |
my $try = int( ($low+$high) / 2 ); | |
$step ++; | |
$low = $try+1, next if $arr->[$try] < $word; | |
$high = $try-1, next if $arr->[$try] > $word; | |
return [$try, $step]; | |
} | |
[undef, $step]; | |
} | |
1; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment