Skip to content

Commit 3491cb2

Browse files
authored
Merge pull request #68 from gurucharan2206/GurucharancppLocal
BetterSequentialSearch function added to SequentialSearch.h
2 parents ff14ce5 + ec3ade0 commit 3491cb2

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

Algorithm/SequentialSearch.h

+16
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,20 @@ int SequentialSearch(vector<int>& v, int k) {
44
if (v[i] == k)
55
return i;
66
return -1;
7+
}
8+
9+
10+
/* The following is a Sentinel Search Algorithm which only performs
11+
just one test in each loop iteration thereby reducing time complexity */
12+
13+
int BetterSequentialSearch(vector<int>& v, int k) {
14+
int last = v[v.size()-1];
15+
v[v.size()-1] = k;
16+
int i = 0;
17+
while (v[i]!= k)
18+
i++;
19+
v[v.size()-1] = last;
20+
if(i < v.size()-1 || v[v.size()-1] == k)
21+
return i;
22+
return -1;
723
}

0 commit comments

Comments
 (0)