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;
|
2020-09-02 01:59:04 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/* 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
|
|
|
}
|