function idx = binary_search(X, value)
%Binary search for optimized searching in the sorted array
%
%[IDX]
%   If
%       IDX == 0, then VALUE < X(1)
%       IDX == i, then X(i) <= VALUE < X(i+1), for i = 1,2,...,length(X)-1
%       IDX == length(X), then X(end) <= VALUE
%BINARY_SEARCH(X, VALUE)
%   X   Sorted array to search in
%   VALUE   Value to compare
left = 1;
right = length(X);
% Check the borders immediately
if value < X(1)
    idx = 0; return
elseif value >= X(end)
    idx = right; return
end
% Otherwise
while left < right
  idx = 1 + floor((left+right-1) / 2);
  if value < X(idx)
    right = idx - 1;
  elseif value >= X(idx) 
    left = idx;
  end
end
idx = left;