I have a sorted (increasing) array of real values, name it (duplication is possible). I want to find, given the range of values ββ[x, y], all indexes of values ββ(i) for which there is an index j such that: j> i and x <= a [j] -a [i] <= y Or just put, find the values ββin which there is a βforward differenceβ in the given range.
The output is a logical array of length a.Length. Since the array is sorted in all different directions, x and y are positive.
The best Ive managed to do is start with each index looking at the subarray in front of it and do a binary search for x + a [i] and check if [j] <= y + a [i], I think that it is O (n log n). Is there a better approach? Or something I can do to speed things up.
I should note that in the end I want to search for many such ranges [x, y] in the same array a, but the number of ranges is much less than the length of the array (4-6 orders of magnitude less), so Im much more interested the complexity of the search.
Example:
a= 0, 1, 46, 100, 185, 216, 285
with the range x, y = [99,101] should be returned:
[true, true, false, false, true, false, false]
For values ββof 0.1 and 185 only, is there a forward difference within the range.
Code from memory may have some errors:
int bin_search_closesmaller(int arr[], int key, int low, int high) { if (low > high) return high; int mid = (high - low)/2; if (arr[mid] > key) return bin_search_closesmaller(arr, key, low, mid - 1); if (arr[mid] < key) return bin_search_closesmaller(arr, key, mid + 1, high); return mid; } bool[] findDiffs(int[] a, int x, int y) { bool[] result = new bool[a.Length]; for(int i=0; i<a.Length-1;i++) { int idx=bin_search_closesmaller(a, y+a[i], i+1, a.Length-1); if (idx==-1) continue; if (a[idx]-a[i] >= x) result[i]=true; } }
Thanks!