Skip to content

Commit d568f9f

Browse files
committed
addded solution for binary search
1 parent 21be22c commit d568f9f

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

binarySearch.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,13 @@
11
// Task: write a function which accepts a sorted array and a value and returns the index at which the value exists. Otherwise, return -1.
2+
3+
const binarySearch = (arr, elem) => {
4+
var start = 0;
5+
var end = arr.length - 1;
6+
var middle = Math.floor((start + end) / 2);
7+
while (arr[middle] !== elem && start <= end) {
8+
if (elem < arr[middle]) end = middle - 1;
9+
else start = middle + 1;
10+
middle = Math.floor((start + end) / 2);
11+
}
12+
return arr[middle] === elem ? middle : -1;
13+
};

0 commit comments

Comments
 (0)