forked from mgechev/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursive-binarysearch.js
More file actions
49 lines (45 loc) · 1.44 KB
/
Copy pathrecursive-binarysearch.js
File metadata and controls
49 lines (45 loc) · 1.44 KB
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
46
47
48
49
(function (exports) {
'use strict';
/**
* Recursive version of binary search. It's complexity is O(log n).
*
* @public
*/
var binarySearch = (function () {
/**
* Binary search.
*
* @pivate
* @param {array} array Array where we should find the index of the element
* @param {number} key Key of the element which index should be found
* @param {number} left Left index
* @param {number} right Right index
* @returns {number} index The index of the element or -1 if not found
*
*/
function recursiveBinarySearch(array, key, left, right) {
if (left > right) {
return -1;
}
var middle = Math.floor((right + left) / 2);
if (array[middle] === key) {
return middle;
} else if (array[middle] > key) {
return recursiveBinarySearch(array, key, left, middle - 1);
} else {
return recursiveBinarySearch(array, key, middle + 1, right);
}
}
/**
* Calls the binary search function with it's initial values.
*
* @param {array} array The input array
* @param {number} key The key of the element which index should be found
* @returns {number} index The index of the element or -1 if not found
*/
return function (array, key) {
return recursiveBinarySearch(array, key, 0, array.length);
};
}());
exports.binarySearch = binarySearch;
}(typeof exports === 'undefined' ? window : exports));