Skip to content

Commit e6fed13

Browse files
committed
recursive binary search in js
1 parent 8e46e41 commit e6fed13

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
function binarySearch(arr, val, start = 0, end = arr.length - 1) {
2+
const mid = Math.floor((start + end) / 2);
3+
4+
if (val === arr[mid]) {
5+
return mid;
6+
}
7+
8+
if (start >= end) {
9+
return -1;
10+
}
11+
12+
return val < arr[mid]
13+
? binarySearch(arr, val, start, mid - 1)
14+
: binarySearch(arr, val, mid + 1, end);
15+
}
16+
17+
let arr = [1, 2, 4, 6, 100, 10000];
18+
19+
console.log(binarySearch(arr, 2));

0 commit comments

Comments
 (0)