-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbinary_search.js
More file actions
45 lines (36 loc) · 844 Bytes
/
Copy pathbinary_search.js
File metadata and controls
45 lines (36 loc) · 844 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
* Performs a Binary search
* * Hint: works on sorted arrays
*
* @param {array} arr
* @param {string|int} toSearch
* @returns -1 | toSearch
*/
function binarySearch(arr, toSearch) {
var max = arr.length - 1;
var middle = Math.floor(max / 2);
var min = 0;
if (!Number.isInteger(toSearch)) {
return -1;
}
if (arr[max] === toSearch) {
return max;
}
if (arr[min] === toSearch) {
return min;
}
while(max >= min) {
if (arr[middle] === toSearch) {
return middle;
}
if (arr[middle] > toSearch) {
max = middle - 1;
}
if (arr[middle] < toSearch) {
min = middle + 1;
}
middle = Math.floor((min + max) / 2);
}
return -1;
}
console.log(binarySearch([1,2,3,4,5], 5));