简体   繁体   中英

finding a smaller number than a given number in a very large array without linear search

I want to find last occurrence of a number smaller or equal than a given number. Since the integer vector is very very large, O(n) is not that efficient.

I divided the vector into two parts and parallel searched.

Lets understand with an example:-

vector <int> arr = {1, 8, 7, 1, 2, 9, 5, 7, 4 ,6};

I want to find last occurence of a number smaller or equal to say 2, so I divided the array into two:

{1, 8, 7, 1, 2} and {9, 5, 7, 4, 6}

and started searching from end in both arrays.

As we can see, a number smaller or equal to 2 is at position 5 (index 4) but it could have been at any position greater than 5 so we still have to search second array entirely since our objective is to find the element at maximum index.

I want to ask if there is any stl function to find such number lesser than 2 in second array so that I do not have search the second array entirely.

Can I use std::find to find a number smaller than 2 in the second array?

EDIT: a number smaller or equal to 2 is at position 5 (index 4) but it could have been at any position greater than 5, so we stop at position 5 in the first array but continue searching second array. Suppose we get element 1 at position 7(index 6), since 7 > 5 so we just return position 7 and program ends. This saved us from searching the first array entirely.

Since we're starting with a vector, we are bound to inspect every element if we search from beginning to end.

However, if we search from end to beginning, we can stop as soon as the predicate is satisfied. This makes the algorithm worst-case O(N) and best-case O(1).

#include <vector>
#include <algorithm>
#include <iostream>


int main()
{
    auto arr = std::vector <int>{ 1, 8, 7, 1, 2, 9, 5, 7, 4 ,6 };

    auto less_than_three = [](auto&& x) { return x < 3; };

    auto rpos = std::find_if(rbegin(arr), rend(arr), less_than_three);

    if (rpos == rend(arr))
    {
        std::cout << "not found\n";
    }
    else
    {
        auto pos = prev(rpos.base());
        auto index = distance(begin(arr), pos);
        std::cout << "found at position " << index << "\n";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM