Skip to content

Instantly share code, notes, and snippets.

@western
Last active February 27, 2017 15:50
Show Gist options
  • Save western/e52acd80af18355a5be676de51a5e1be to your computer and use it in GitHub Desktop.
Save western/e52acd80af18355a5be676de51a5e1be to your computer and use it in GitHub Desktop.
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