We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 21be22c commit d568f9fCopy full SHA for d568f9f
binarySearch.js
@@ -1 +1,13 @@
1
// 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