cpp-interview/Algorithm/SequentialSearch.h

23 lines
548 B
C
Raw Normal View History

2018-02-11 01:08:43 +08:00
// 顺序查找
int SequentialSearch(vector<int>& v, int k) {
2018-03-09 22:41:55 +08:00
for (int i = 0; i < v.size(); ++i)
if (v[i] == k)
2018-02-11 01:08:43 +08:00
return i;
2018-03-09 22:41:55 +08:00
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;
2018-02-11 01:08:43 +08:00
}