IRootLab
An Open-Source MATLAB toolbox for vibrational biospectroscopy
bsearch.m
Go to the documentation of this file.
1 %>@ingroup maths
2 %>@file
3 %>@brief Binary Search
4 %>
5 %> Written by Aroh Barjatya
6 %>
7 %> Binary search for values specified in vector 'var' within data vector 'x'
8 %> The data has to be pre-sorted in ascending or decending order
9 %> There is no way to predict how the function will behave if there
10 %> are multiple numbers with same value.
11 %> returns the index values of the searched numbers
12 %>
13 %> @c flag_bin added by JT. @c flag_bin = 1 will cause to return the index corresponding to the highest number in case
14 %> of @c var being between two numbers.
15 %
16 %> @param x
17 %> @param var
18 %> @param flag_bin
19 %> @return @em index
20 function index = bsearch(x,var, flag_bin)
21 
22 if nargin < 3
23  flag_bin = 0;
24 end;
25 
26 xLen = length(x);
27 [xRow xCol] = size(x);
28 if x(1) > x(xLen) % means x is in descending order
29  if xRow==1
30  x = fliplr(x);
31  else
32  x = flipud(x);
33  end
34  flipped = 1;
35 elseif x(1) <= x(xLen) % means x is in ascending order
36  flipped = 0;
37 else
38  'badly formatted data. Type ''help bsearch\'')';
39  return;
40 end
41 
42 for i = 1:length(var)
43  low = 1;
44  high = xLen;
45  if var(i) <= x(low)
46  index(i) = low;
47  continue;
48  elseif var(i) >= x(high)
49  index(i) = high;
50  continue;
51  end
52  flag = 0;
53  while (low <= high)
54  mid = round((low + high)/2);
55  if (var(i) < x(mid))
56  high = mid;
57  elseif (var(i) > x(mid))
58  low = mid;
59  else
60  index(i) = mid;
61  flag = 1;
62  break;
63  end
64  if (low == high - 1)
65  break
66  end
67  end
68  if (flag == 1)
69  continue;
70  end
71  if (low == high)
72  index(i) = low;
73  elseif flag_bin || ((x(low) - var(i))^2 > (x(high) - var(i))^2)
74  index(i) = high;
75  else
76  index(i) = low;
77  end
78 end
79 
80 if flipped
81  index = xLen - index + 1;
82 end
Pre-processing block base class.
Definition: pre.m:2
function bsearch(in x, in var, in flag_bin)