forked from nas5w/javascript-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexponentialSearch.js
More file actions
31 lines (25 loc) · 770 Bytes
/
exponentialSearch.js
File metadata and controls
31 lines (25 loc) · 770 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
const binarySearch = require("./binarySearch");
/**
* Exponential search - A slight optimization for binary search,
* finds an upper bound for where the item can be, then
* performs binary search on this smaller sublist.
*
* Useful for unbounded lists.
*
* Big O = (log n)
* @param {*} list to search from
* @param {*} itemToFind item we want to find
*/
function exponentialSearch(list, itemToFind) {
if(list.length <= 1) return false;
let bound = 1;
while(bound < list.length && list[bound] < itemToFind) {
bound *= 2;
}
if(bound < list.length) {
// element can only between bound/2 and bound indices
return binarySearch(list.slice(bound / 2 ,bound), itemToFind);
}
return false;
}
module.exports = exponentialSearch;