Skip to content

Commit ec3ade0

Browse files
author
Gurs
committed
Added a better way of Sequential search to existing file
1 parent ff14ce5 commit ec3ade0

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

Algorithm/SequentialSearch.h

Lines changed: 16 additions & 0 deletions
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)