Added a better way of Sequential search to existing file

This commit is contained in:
Gurs 2020-09-01 23:29:04 +05:30
parent ff14ce5c49
commit ec3ade0e35

View File

@ -5,3 +5,19 @@ int SequentialSearch(vector<int>& v, int 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;
}