Skip to content
This repository was archived by the owner on Jun 2, 2024. It is now read-only.

Commit 4393ba8

Browse files
authored
Add binary search in JavaScript (#915)
1 parent 3065c25 commit 4393ba8

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
function binarySearch(sortedArray, key){
2+
let start = 0;
3+
let end = sortedArray.length - 1;
4+
5+
while (start <= end) {
6+
let middle = Math.floor((start + end) / 2);
7+
8+
if (sortedArray[middle] === key) {
9+
// found the key
10+
return middle;
11+
} else if (sortedArray[middle] < key) {
12+
// continue searching to the right
13+
start = middle + 1;
14+
} else {
15+
// search searching to the left
16+
end = middle - 1;
17+
}
18+
}
19+
// key wasn't found
20+
return -1;
21+
}

0 commit comments

Comments
 (0)