線形探索
データの集合から目的の値を探し出すアルゴリズムです。
集合内一つ一つを評価していくためデータ量が多い場合は重い処理になります。
線形探索を行う実装例
LinearSearch.ts
function linearSearch(arr: number[], target: number): number {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
//値が見つかった場合はそのインデックスを返す
return i;
}
}
//値が見つからなかった場合は-1を返す
return -1;
}
//使用例です
const numbers = [10, 22, 35, 40, 55, 67];
//以下は見つける対象の数値
const targetValue = 35;
const index = linearSearch(numbers, targetValue);
if (index !== -1) {
console.log(`値 ${targetValue} は ${index} 番目です`);
} else {
console.log(`値 ${targetValue} は配列内に見つかりませんでした。`);
}
linearSearch
関数に評価したい数値配列と、特定したい数値を渡すと探索が始まるようになっています。