forked from sccn/mobilab
-
Notifications
You must be signed in to change notification settings - Fork 1
/
binary_findClosest.m
52 lines (44 loc) · 1.04 KB
/
binary_findClosest.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
% vector is a monotonically increasing sorted vector.
function ind = binary_findClosest(vector,target)
%
% N = length(vector);
%
% if N <= 5
% [~,ind] = min(abs(vector - target));
% return;
% end
%
%
% ind = ceil(N/2);
% if vector(ind) > target
% ind = binary_findClosest(vector(1:ind-1),target);
% else
% if vector(ind) == target
% return;
% else
% subind = binary_findClosest(vector(ind+1:end),target);
% ind = ind + subind;
% return;
% end
% end
N = length(vector);
startInd = 1;
endInd = N;
while N > 5
ind = ceil(N/2);
if vector(startInd + ind - 1) > target
%startInd = startInd;
endInd = startInd+ ind - 2;
else
if vector(startInd + ind - 1) == target
ind = startInd + ind - 1;
return;
else
startInd = startInd + ind;
%endInd = endInd;
end
end
N = endInd - startInd + 1;
end
[~,ind] = min(abs(vector(startInd:endInd)-target));
ind = ind + startInd - 1;