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
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)).
This could be solved by using some tricks. In an unsorted array simly if we traverse through it, the complexity in worst case (when element is present at last index) would be O(N), where N is the size of array. So, here is the trick. First check the last index so that if the element is present at last index (the worst case) our code will be executed in O(1). and after that while the code to traverse and find the element. So, now the worst case complexity would be O(N-1).
int findElement(int N, int arr[], int element){
if(arr[N]==element){
return i;
}
for(int i=0; i<N-1; i++){
if(arr[i]==element)
return i;
}
return -1;
}
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++
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 get 2*log_2(n)
, which is O(log_2(n))
with the witness C = 2
.