Skip to content

Commit 9db8197

Browse files
committed
feat: add binary search recursive version
1 parent 1a06e55 commit 9db8197

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
function binarySearch(array, element, first = 0, last = array.length - 1) {
2+
if (first > last) return null;
3+
4+
let mid = Math.floor(first + last) / 2;
5+
if (array[mid] === element) return mid;
6+
if (array[mid] < element) return binarySearch(array, element, mid + 1, last);
7+
else return binarySearch(array, element, first, mid - 1);
8+
}
9+
10+
const data = [1, 2, 5, 6, 8, 14, 16];
11+
const elements = [14, 32, 15, 2, 1];
12+
13+
elements.forEach(element => console.log(element, binarySearch(data, element)));
14+

0 commit comments

Comments
 (0)