Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d59cc09

Browse files
authored
Merge pull request knaxus#78 from gabrielbarker/jumpSearch
Add jumpSearch and Tests
2 parents 7ca7bd9 + 9d2da8f commit d59cc09

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
const { jumpSearch, jumpSearchRecursive } = require('.');
2+
3+
describe('Jump Search', () => {
4+
const array = [1, 2, 3, 4, 5, 6, 7, 8];
5+
describe('When element to find is at 1st position ', () => {
6+
it('Jump search', () => {
7+
expect(jumpSearch(array, 1)).toEqual(0);
8+
});
9+
});
10+
describe('When element to find is at last position ', () => {
11+
it('Jump search', () => {
12+
expect(jumpSearch(array, 7)).toEqual(6);
13+
});
14+
});
15+
describe('When element to find is at random position ', () => {
16+
it('Jump search', () => {
17+
expect(jumpSearch(array, 3)).toEqual(2);
18+
});
19+
});
20+
});

‎src/_Searching_/JumpSearch/index.js‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Note: Array must be sorted for jump search
3+
* Complexity:
4+
* Worst case time complexity: O(√N)
5+
* Average case time complexity: O(√N)
6+
* Best case time complexity: O(1)
7+
* Space complexity: O(1)
8+
*/
9+
function jumpSearch(arr, key) {
10+
const n = arr.length;
11+
const jump = Math.floor(Math.sqrt(n));
12+
let step = jump;
13+
14+
let prev = 0;
15+
16+
while(arr[Math.min(step, n) - 1] < key) {
17+
prev = step;
18+
step += jump;
19+
if (prev >= n)
20+
return null;
21+
}
22+
23+
while(arr[prev] < key) {
24+
prev++;
25+
26+
if (prev == Math.min(step, n))
27+
return null;
28+
}
29+
30+
if (arr[prev] == key)
31+
return prev;
32+
33+
return null;
34+
}
35+
36+
module.exports = {
37+
jumpSearch,
38+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /