-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinarySearch.js
29 lines (28 loc) · 931 Bytes
/
binarySearch.js
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
function binarySearch(array, index) {
let start = 0;
let end = array.length - 1;
let middle = Math.floor((start + end) / 2);
while (array[middle] !== index && start <= end) {
index < array[middle] ?
end = middle - 1 :
start = middle + 1;
middle = Math.floor((start + end) / 2)
}
return array[middle] === index ? middle : - 1;
}
console.log(binarySearch([1, 2, 3, 4, 5], 2)) // 1
console.log(binarySearch([1, 2, 3, 4, 5], 3)) // 2
console.log(binarySearch([1, 2, 3, 4, 5], 5)) // 4
console.log(binarySearch([1, 2, 3, 4, 5], 6)) // -1
console.log(binarySearch([
5, 6, 10, 13, 14, 18, 30, 34, 35, 37,
40, 44, 64, 79, 84, 86, 95, 96, 98, 99
], 10)) // 2
console.log(binarySearch([
5, 6, 10, 13, 14, 18, 30, 34, 35, 37,
40, 44, 64, 79, 84, 86, 95, 96, 98, 99
], 95)) // 16
console.log(binarySearch([
5, 6, 10, 13, 14, 18, 30, 34, 35, 37,
40, 44, 64, 79, 84, 86, 95, 96, 98, 99
], 100)) // -1