;/* ---------------------------------------------------------------------- ; Find the nearest element in an array to the given value. ; This version uses a binary search for speed. ; The array must be sorted for this to work. ; Input: xx (given value). ; Input: narr (number of elements in array). ; Input: arr (the array to be searched). ; Array MUST be sorted, low values to high values. ;*/ function cneari_bs, xx, narr, arr ; Binary search. if (narr le 1L) then return, 0L ii=0L i1=0L i2=narr-1L while ((i2-i1) gt 1L) do begin ii = (i1+i2)/2 if (arr[ii] gt xx) then i2=ii else i1=ii endwhile if (i2 le i1) then printf,-2,"***ERROR: cneari_bs: this should not happen." if ( ABS((arr[i1] - xx)) le ABS((arr[i2] - xx)) ) then kk=i1 else kk=i2 return,kk end