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 it's not sorted, you have to inspect each element.
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:-
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
map<int,int> map;
for(int i=0;i<n;i++){
int k;
cin>>k;
map[k]=1;
}
int num;
cin>>num;
if(map[num]){
cout<<"FOUND"<<endl;
}else{
cout<<"NOT FOUND"<<endl;
}
return 0;
}
Input:
5 // *no. of elements*
6 4 7 3 2 //*elements*
3 // *number to find*
Output :FOUND
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?
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
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'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.