-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarSort.js
More file actions
24 lines (20 loc) · 782 Bytes
/
BinarSort.js
File metadata and controls
24 lines (20 loc) · 782 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
function binarySearch(list, value) {
// initial values for start, middle and end
let start = 0;
let stop = list.length - 1;
let middle = Math.floor((start + stop) / 2);
// While the middle is not what we're looking for and the list does not have a single item
while (list[middle] !== value && start < stop) {
if (value < list[middle]) {
stop = middle - 1;
} else {
start = middle + 1;
}
// recalculate middle on every iteration
middle = Math.floor((start + stop) / 2);
}
// if the current middle item is what we're looking for return it's index, else return -1
return (list[middle] !== value) ? -1 : middle;
}
const list = [2, 5, 8, 9, 13, 45, 67, 99];
console.log(binarySearch(list, 99)); // 7 -> returns the index of the item