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

Add jumpSearch and Tests #78

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
TheSTL merged 2 commits into knaxus:master from rubysdeadname:jumpSearch
Oct 13, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/_Searching_/JumpSearch/JumpSearch.test.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const { jumpSearch, jumpSearchRecursive } = require('.');

describe('Jump Search', () => {
const array = [1, 2, 3, 4, 5, 6, 7, 8];
describe('When element to find is at 1st position ', () => {
it('Jump search', () => {
expect(jumpSearch(array, 1)).toEqual(0);
});
});
describe('When element to find is at last position ', () => {
it('Jump search', () => {
expect(jumpSearch(array, 7)).toEqual(6);
});
});
describe('When element to find is at random position ', () => {
it('Jump search', () => {
expect(jumpSearch(array, 3)).toEqual(2);
});
});
});
38 changes: 38 additions & 0 deletions src/_Searching_/JumpSearch/index.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,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,
};

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