Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix 002_search linearSearch/binarySearch(feature-004_algorithm_002_search) #3

Merged
merged 4 commits into from Mar 19, 2024
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
38 changes: 33 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,33 @@ function linearSearch (array, target) {
* [1, 2, 3, 4] 5 => -1
*/

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

//左端が右端以下の間(1つの要素に絞られるまで)は処理を続ける
while (low <= high) {
mid = low + high; // 真ん中の位置
yko-git marked this conversation as resolved.
Show resolved Hide resolved
guess = array[mid]; // 真ん中の要素

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

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

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