0
0

【TypeScriptで学ぶアルゴリズム】線形探索

Posted at

線形探索

データの集合から目的の値を探し出すアルゴリズムです。
集合内一つ一つを評価していくためデータ量が多い場合は重い処理になります。

線形探索を行う実装例

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関数に評価したい数値配列と、特定したい数値を渡すと探索が始まるようになっています。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0