Skip to content

Commit

Permalink
Merge pull request #3 from yko-git/feature-004_algorithm_002_search
Browse files Browse the repository at this point in the history
fix 002_search linearSearch/binarySearch(feature-004_algorithm_002_search)
  • Loading branch information
yko-git committed Mar 19, 2024
2 parents ed56c1f + 1d070b8 commit dbb2adc
Showing 1 changed file with 35 additions and 5 deletions.
40 changes: 35 additions & 5 deletions 004_algorithm/002_search.js
@@ -1,4 +1,3 @@

/**
* 2.3.1 リニアサーチ
*
Expand All @@ -11,7 +10,13 @@
* [5, 3, 2, 1], 6 => -1
*/

function linearSearch (array, target) {
function linearSearch(array, target) {
for (let i = 0; i < array.length; i++) {
if (array[i] === target) {
return i;
}
}
return -1;
}

/**
Expand All @@ -24,10 +29,35 @@ function linearSearch (array, target) {
* [1, 2, 3, 4] 5 => -1
*/

function binarySearch (array, target) {
function binarySearch(array, target) {
// 配列の位置を設定
let index = -1;
let low = 0; //左端
let high = array.length - 1; //右端

//左端が右端以下の間(1つの要素に絞られるまで)は処理を続ける
while (low <= high) {
let mid = Math.floor((low + high) / 2); // 真ん中の位置
let guess = array[mid]; // 真ん中の要素

//真ん中の要素がtargetと合致したら
if (guess == target) {
//位置を返す
index = mid;
return index;

//真ん中の要素がtargetより大きかったら
} else if (guess > target) {
//右端の位置は要素の位置-1
high = mid - 1;
} else {
low = mid + 1;
}
}
return index;
}

module.exports = {
linearSearch,
binarySearch
}
binarySearch,
};

0 comments on commit dbb2adc

Please sign in to comment.