forked from SF-WDI-LABS/binary-search
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample-solution.js
More file actions
31 lines (30 loc) · 883 Bytes
/
example-solution.js
File metadata and controls
31 lines (30 loc) · 883 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function binarySearch(searchArray, searchElement) {
// declare variables for high, low, and mid points of the array
var min = 0;
var max = searchArray.length - 1;
var mid;
var currentElement;
// while the low is less than the high
while (min <= max) {
// set mid equal to halfway between the low and the high
mid = Math.floor((min + max) / 2);
// grab the value of the mid element
currentElement = searchArray[mid];
// target is to the right
if (currentElement < searchElement) {
// cut out the left half of the collection
min = mid + 1;
}
// target is to the left
else if (currentElement > searchElement) {
// cut out the right half of the collection
max = mid - 1;
}
else {
// target has been found as currentElement is searchElement
return mid;
}
}
// not found
return -1;
}