function L = binarySearch(x, v)
% Find position after which to insert x (or find position of x in v).
% x is the scalar search target.
% v is a vector of numbers sorted in ascending order.
% L is the index such that v(L) <= x < v(L+1);
% L=0 if xv(end), L=length(v) but x~=v(L).
% Maintain a search window [L,R] such that v(L) <= x < v(R).
% Since x may not be in v, initially set ...
L=0; R=length(v)+1;
% Keep halving [L,R] until R-L is 1, always keeping v(L) <= x < v(R)
while R ~= L+1
m= floor((L+R)/2); % middle of search window
if v(m) <= x
L= m;
else
R= m;
end
end
if L==0 || v(L)~=x
fprintf(' %g not found', x)
end