Home > matutils > binsearch.m

binsearch

PURPOSE ^

bsearch(x,var)

SYNOPSIS ^

function index = bsearch(x,var)

DESCRIPTION ^

 bsearch(x,var)
 Written by Aroh Barjatya
 Binary search for values specified in vector 'var' within data vector 'x'
 The data has to be pre-sorted in ascending or decending order
 There is no way to predict how the function will behave if there 
 are multiple numbers with same value.
 returns the index values of the searched numbers

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SOURCE CODE ^

0001 % bsearch(x,var)
0002 % Written by Aroh Barjatya
0003 % Binary search for values specified in vector 'var' within data vector 'x'
0004 % The data has to be pre-sorted in ascending or decending order
0005 % There is no way to predict how the function will behave if there
0006 % are multiple numbers with same value.
0007 % returns the index values of the searched numbers
0008 
0009 function index = bsearch(x,var)
0010 
0011 xLen = length(x);
0012 [xRow xCol] = size(x);
0013 if x(1) > x(xLen)% means x is in descending order
0014   if xRow==1
0015     x = fliplr(x);  
0016   else
0017     x = flipud(x);
0018   end
0019   flipped = 1;
0020 elseif x(1) < x(xLen)% means x is in ascending order
0021   flipped = 0;
0022 else
0023   'badly formatted data. Type ''help bsearch\'')';
0024   return;
0025 end
0026 
0027 for i = 1:length(var)
0028   low = 1;
0029   high = xLen;
0030   if var(i) <= x(low)
0031     index(i) = low;
0032     continue;
0033   elseif var(i) >= x(high)
0034     index(i) = high;
0035     continue;
0036   end
0037   flag = 0;
0038   while (low <= high)
0039     mid = round((low + high)/2);
0040     if (var(i) < x(mid))
0041       high = mid;
0042     elseif (var(i) > x(mid))
0043       low = mid;
0044     else
0045       index(i) = mid;
0046       flag = 1;
0047       break;
0048     end
0049     if (low == high - 1)
0050       break
0051     end
0052   end
0053   if (flag == 1)
0054     continue;
0055   end
0056   if (low == high)
0057     index(i) = low;
0058   elseif ((x(low) - var(i))^2 > (x(high) - var(i))^2)
0059     index(i) = high;
0060   else
0061     index(i) = low;
0062   end
0063 end
0064 
0065 if flipped
0066   index = xLen - index + 1;
0067 end
0068 
0069 return;

Generated on Sun 14-Jun-2015 17:12:45 by m2html © 2005