forked from mgechev/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.js
More file actions
31 lines (28 loc) · 861 Bytes
/
Copy pathbinarysearch.js
File metadata and controls
31 lines (28 loc) · 861 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 (exports) {
/**
* Searchs for specific element in given array using the binary search algorithm.
* It's complexity is O(log n)
*
* @public
* @param {array} array Input array
* @param {number} key The key of the element which index we should find
* @returns {number} index The index of the element or -1 if not found
*/
function binarySearch(array, key) {
var middle = Math.floor(array.length / 2),
left = 0,
right = array.length;
while (right >= left) {
if (array[middle] === key) {
return middle;
} else if (array[middle] > key) {
right = middle - 1;
} else {
left = middle + 1;
}
middle = Math.floor((left + right) / 2);
}
return -1;
}
exports.binarySearch = binarySearch;
}(typeof exports === 'undefined' ? window : exports));