Fastest way to search for an element in unsorted a

2020-02-26 04:55发布

I just bumped on to this question today and was trying for a solution that is better than O(N) but could not come up with one.

Searched through SO but couldn't find this question.

Is there any solution better than O(n) or is it a problem that cannot be solved better than that?

My initial thought was Binary Search but again for that you need to sort it which is again >n. I also thought of applying quicksort for just the half of the array to which the search element might belong but again we are making n comparisons initially and discarding the other half only later. Am I getting this right or am I looking at the solution in a wrong direction?

I was trying for a solution in c++ and no javascript's IndexOf() or C# Array.find() or LINQ's.

9条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-02-26 05:38

Make it parallel. Divide the array in chunks and search in parallel. The complexity will be O(n) but running time will be much less. Actually it will be proportional to no. of processors you have.

You can use Parallel Patterns Library in C++

查看更多
劫难
3楼-- · 2020-02-26 05:38

You're right, the fastest way is to simply iterate through the array and look for it. Without further information, there is nothing better you can do.

Unless you have a quantum computer, that is.

查看更多
女痞
4楼-- · 2020-02-26 05:39

If you are not doing parallel search, then you can insert key to the end of array as sentinel value and do search with only 'n' comparisons instead of 2n comparisons.

For more details, refer the following question: What's the point of using linear search with sentinel?

查看更多
登录 后发表回答