Skip to content

Commit

Permalink
Merge pull request huihut#68 from gurucharan2206/GurucharancppLocal
Browse files Browse the repository at this point in the history
BetterSequentialSearch function added to SequentialSearch.h
  • Loading branch information
huihut authored Sep 3, 2020
2 parents ff14ce5 + ec3ade0 commit 3491cb2
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions Algorithm/SequentialSearch.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

0 comments on commit 3491cb2

Please sign in to comment.