Skip to content

Commit a292255

Browse files
Merge pull request akshitagit#15 from Tomekmularczyk/master
feat: add binary search example
2 parents e1ddf86 + f31769f commit a292255

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Algorithms/binarySearch.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* Binary search is an efficient algorithm for finding an item from a sorted list of items.
3+
* It works by repeatedly dividing in half the portion of the list that could contain the item,
4+
* until you've narrowed down the possible locations to just one.
5+
*/
6+
7+
function binarySearch(arr, x, left, right) {
8+
if (left > right) {
9+
return false;
10+
}
11+
12+
const middle = Math.floor(left + (right - left) / 2);
13+
if (arr[middle] === x) {
14+
return true;
15+
} else if (x < arr[middle]) {
16+
return binarySearch(arr, x, left, middle - 1);
17+
} else {
18+
return binarySearch(arr, x, middle + 1, right);
19+
}
20+
}
21+
22+
export default function (arr, x) {
23+
return binarySearch(arr, x, 0, arr.length);
24+
}

0 commit comments

Comments
 (0)