私の目標は、標準の線形検索を使用するよりもセンチネルを使用した線形検索を採用する方が好まれる理由を理解することです。
#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;
}
ウィキペディアは次のように述べています。
オーバーヘッドを削減するもう 1 つの方法は、ループ インデックスのすべてのチェックをなくすことです。これは、目的の項目自体を番兵値としてリストの最後に挿入することで実行できます。
センチネルで線形検索を実装する場合は、
array[length + 1] = elementToSearch;
ただし、検索対象の要素が見つかると、ループは配列の要素のチェックを停止します。センチネルで線形検索を使用するポイントは何ですか?