Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d82b065

Browse files
Binary search algorithm
1 parent 8ad8ba1 commit d82b065

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

‎Algorithm/binarySearch.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
function binarySearch(numArray, key) {
2+
let middleIdx = Math.floor(numArray.length / 2);
3+
let middleElem = numArray[middleIdx];
4+
5+
if (middleElem === key) return true;
6+
else if (middleElem < key && numArray.length > 1) {
7+
return binarySearch(numArray.splice(middleIdx, numArray.length), key);
8+
} else if (middleElem > key && numArray.length > 1) {
9+
return binarySearch(numArray.splice(0, middleIdx), key);
10+
} else return false;
11+
}
12+
13+
binarySearch([5, 7, 12, 16, 36, 39, 42, 56, 71], 7); // true

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /