我的目标是了解为什么采用带哨兵的线性搜索比使用标准线性搜索更可取。
#include <stdio.h>
int linearSearch(int array[], int length) {
int elementToSearch;
printf("Insert the element to be searched: ");
scanf("%d", &elementToSearch);
for (int i = 0; i < length; i++) {
if (array[i] == elementToSearch) {
return i; // I found the position of the element requested
}
}
return -1; // The element to be searched is not in the array
}
int main() {
int myArray[] = {2, 4, 9, 2, 9, 10};
int myArrayLength = 6;
linearSearch(myArray, myArrayLength);
return 0;
}
维基百科提到:
另一种减少开销的方法是消除对循环索引的所有检查。这可以通过在列表的远端插入所需的项目本身作为哨兵值来完成。
如果我用哨兵实现线性搜索,我必须
array[length + 1] = elementToSearch;
但是,一旦找到要搜索的元素,循环就会停止检查数组的元素。将线性搜索与哨兵一起使用有什么意义?