From ec3ade0e35a3f7689b14dc904cb30e442d388760 Mon Sep 17 00:00:00 2001 From: Gurs Date: Tue, 1 Sep 2020 23:29:04 +0530 Subject: [PATCH] Added a better way of Sequential search to existing file --- Algorithm/SequentialSearch.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Algorithm/SequentialSearch.h b/Algorithm/SequentialSearch.h index 28fd335..2ef667d 100644 --- a/Algorithm/SequentialSearch.h +++ b/Algorithm/SequentialSearch.h @@ -4,4 +4,20 @@ int SequentialSearch(vector& 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& 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; } \ No newline at end of file