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.
What will be the efficiency of algorithm that makes use of partition approach applied during quick-sort as follows?
Randomly select some value (let us call it v) in the list.
Partition the entire list into 2 parts. Left part contains all elements that are less than v. Right part contains all elements that are greater than v.
Repeat the steps 2, 3 until you determine whether the element exists or does not exist.
I am not sure about the complexity of above algorithm, but looks like it will be definitely less than the complexity of quick-sort algorithm: (n log n).
You can search an element with O(1) using this approach.
Just create a MAP . When you insert a value just then for that key assign value to '1', and to search it again just check if that array is present or not .
Below is the code:-
Output :FOUND
It is possible to make your program run faster than
O(n)
.You start off by sorting the array using the merge sort algorithm, then you use binary search to find the element. Both algoro have a running time of
O(log_2(n))
. Adding these two complexities together, you get2*log_2(n)
, which isO(log_2(n))
with the witnessC = 2
.Yet,there is another logic...
(Even numbers are stored in even address)
First check whether the search element is odd or even
If the search element is"even",then perform search only for even adress(Create loop increment to skip odd address)
For example:
You can divide the element and search in parallel or Use "pivot key" to sort to rest 50 elements or any other search method
If you're searching for one element once, just iterate through it. No possible way to get it faster.
If you're searching multiple times, it would be worth it to index it (or sort it, if you will) and make the following searches fast (log(n)).
If it's not sorted, you have to inspect each element.