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; }
In reply to Re: binary search closest element index
by ikegami
in thread binary search closest element index
by etheral
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |