Last active
December 14, 2015 15:48
-
-
Save akzhan/7a7c65dea4ca591afe2e to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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