Skip to content

Instantly share code, notes, and snippets.

@akzhan
Last active December 14, 2015 15: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 akzhan/7a7c65dea4ca591afe2e to your computer and use it in GitHub Desktop.
Save akzhan/7a7c65dea4ca591afe2e to your computer and use it in GitHub Desktop.
package AkzhanAbdulinFindIndex;
use warnings;
use strict;
use List::BinarySearch qw( binsearch_pos );
sub new {
my ( $class ) = @_;
return bless 1, $class;
}
sub find {
my ( $what, $sorted_list ) = @_;
return undef unless $what && $sorted_list && scalar(@$sorted_list);
return $sorted_list->[0] if scalar(@$sorted_list) == 1;
my $count = 0;
my $pos = binsearch_pos { $count ++; $a <=> $b } $what, @$sorted_list;
return (0, $count ) if $pos == 0;
return ( $pos - 1, $count ) if $pos == scalar(@$sorted_list);
my ( $diff_before, $diff_after ) = ( $what - $sorted_list->[$pos - 1], $sorted_list->[$pos] - $what );
return ( $pos - 1, $count) if $diff_before <= $diff_after;
return ( $pos, $count);
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment