mirror of
https://github.com/huihut/interview.git
synced 2025-12-18 21:14:38 +03:00
Added a better way of Sequential search to existing file
This commit is contained in:
@@ -5,3 +5,19 @@ int SequentialSearch(vector<int>& v, int k) {
|
|||||||
return i;
|
return i;
|
||||||
return -1;
|
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;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user