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 fa71c76

Browse files
Create binary_search.js
1 parent 93001c7 commit fa71c76

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

‎algorithms/binary_search.js‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
3+
Search a give key from a provided array.
4+
Use recursion to avoid time complexity of O(n)
5+
6+
*/
7+
8+
9+
function binarySearch(arr, key){
10+
11+
const middleIndex = Math.floor(arr.length / 2);
12+
const middleElement = arr[middleIndex];
13+
14+
if (key === middleElement) return true;
15+
16+
else if (key < middleElement && arr.length > 1){
17+
return binarySearch(arr.splice(0, middleIndex), key);
18+
}
19+
20+
else if (key > middleElement && arr.length > 1){
21+
return binarySearch(arr.splice(middleIndex, arr.length - middleIndex), key);
22+
}
23+
24+
else return false;
25+
26+
}
27+
28+
const arr = [11,12,13,14,15,16];
29+
binarySearch(arr, 15);
30+
31+

0 commit comments

Comments
(0)

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