mirror of
https://github.com/huihut/interview.git
synced 2024-03-22 13:10:48 +08:00
Added a better way of Sequential search to existing file
This commit is contained in:
parent
ff14ce5c49
commit
ec3ade0e35
|
@ -4,4 +4,20 @@ int SequentialSearch(vector<int>& v, int k) {
|
|||
if (v[i] == k)
|
||||
return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
/* The following is a Sentinel Search Algorithm which only performs
|
||||
just one test in each loop iteration thereby reducing time complexity */
|
||||
|
||||
int BetterSequentialSearch(vector<int>& v, int k) {
|
||||
int last = v[v.size()-1];
|
||||
v[v.size()-1] = k;
|
||||
int i = 0;
|
||||
while (v[i]!= k)
|
||||
i++;
|
||||
v[v.size()-1] = last;
|
||||
if(i < v.size()-1 || v[v.size()-1] == k)
|
||||
return i;
|
||||
return -1;
|
||||
}
|
Loading…
Reference in New Issue
Block a user