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 e0e1846

Browse files
Add jumpSearch and Tests
implemented time complextiy
1 parent 9b6f8f5 commit e0e1846

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-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: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
function jumpSearch(arr, key) {
2+
// treat jumps larger than array size as linear search
3+
const n = arr.length;
4+
const jump = Math.floor(Math.sqrt(n));
5+
let step = jump;
6+
7+
let prev = 0;
8+
9+
while(arr[Math.min(step, n) - 1] < key) {
10+
prev = step;
11+
step += jump;
12+
if (prev >= n)
13+
return null;
14+
}
15+
16+
while(arr[prev] < key) {
17+
prev++;
18+
19+
if (prev == Math.min(step, n))
20+
return null;
21+
}
22+
23+
if (arr[prev] == key)
24+
return prev;
25+
26+
return null;
27+
}
28+
29+
module.exports = {
30+
jumpSearch,
31+
};

0 commit comments

Comments
(0)

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