forked from knaxus/problem-solving-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
38 lines (31 loc) · 738 Bytes
/
index.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
30
31
32
33
34
35
36
37
38
/**
* Note: Array must be sorted for jump search
* Complexity:
* Worst case time complexity: O(√N)
* Average case time complexity: O(√N)
* Best case time complexity: O(1)
* Space complexity: O(1)
*/
function jumpSearch(arr, key) {
const n = arr.length;
const jump = Math.floor(Math.sqrt(n));
let step = jump;
let prev = 0;
while(arr[Math.min(step, n) - 1] < key) {
prev = step;
step += jump;
if (prev >= n)
return null;
}
while(arr[prev] < key) {
prev++;
if (prev == Math.min(step, n))
return null;
}
if (arr[prev] == key)
return prev;
return null;
}
module.exports = {
jumpSearch,
};