in reply to binary search closest element index
Use the code in Re: Binary search algorithm.. If the returned value is negative, use the closest of $array[~$idx - 1] and $array[~$idx]
my $idx = binsearch { $a <=> $b } $val, @array; if ($idx < 0) { $idx = ~$idx; --$idx if $idx > 0 && $val - $array[$idx-1] <= $array[$idx] - $val; }
|
|---|