I need to find elements of a vector that are less than one of more elements that come after it. It\'s easy to do in a loop:
x = some_vector_values;
for m = 1
This uses a divide-and-conquer approach (similar to binary search):
Although I haven't done a careful analysis, I think average complexity is O(n), or at most O(n log n). Memory is O(n).
The result is a logical vector ind
that contains true
for accepted elements and false
for rejected elements. The final result would be x(ind)
.
x = [3 4 3 5 6 3 4 1];
n = numel(x);
ind = false(1,n); %// intiallization
s = 1; %// starting index of the part of x that remains to be analyzed
while s <= n %// if s > n we have finished
[~, m] = max(x(s:end)); %// index of maximum within remaining part of x
ind(s:s-2+m) = true; %// elements to its left are accepted
s = s+m; %// update start of remaining part
end
Running time could be reduced a little by changing the while
condition to while s < n
, because the last element is always rejected.