Skip to content
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

Feature: Jump Search #57

Merged
merged 2 commits into from
Oct 7, 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
23 changes: 23 additions & 0 deletions src/algorithms/searching/jumpSearch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
function jumpSearch(list, itemToFind, jumpSize = 4) {
let step = Math.floor(Math.sqrt(jumpSize));
let prev = 0;
while (list[Math.min(step, list.length) - 1] < itemToFind) {
prev = step;
step = step + jumpSize;
if (prev >= list.length) {
return false;
}
}
while (list[parseInt(prev)] < itemToFind) {
prev++;
if (prev == Math.min(step, list.length)) {
return false;
}
}
if (list[parseInt(prev)] === itemToFind) {
return true;
}
return false;
}

module.exports = jumpSearch;
40 changes: 40 additions & 0 deletions test/algorithms/searching/jumpSearch.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const jumpSearch = require("../../../src/algorithms/searching/jumpSearch");

describe("Jump Search algorithm", () => {
it("tests for item does exist", () => {
const arr1 = [1, 3, 5, 7, 8, 9];
const result = jumpSearch(arr1, 8, 7);
expect(result).toBe(true);
});
it("tests for item does not exist and item is less than biggest element", () => {
const arr1 = [1, 3, 5, 7, 8, 9];
const result = jumpSearch(arr1, 2);
expect(result).toBe(false);
});

it("tests for item does not exist", () => {
const arr1 = [1, 3, 5, 7, 8, 9];
const result = jumpSearch(arr1, 200, 20);
expect(result).toBe(false);
});
it("tests for item does exist when jumpSize is valid", () => {
const arr1 = [1, 3, 5, 7, 8, 9];
const result = jumpSearch(arr1, 8, 7, 2);
expect(result).toBe(true);
});
it("tests for item does not exist when jumpSize is valid", () => {
const arr1 = [1, 3, 5, 7, 8, 9];
const result = jumpSearch(arr1, 4, 1);
expect(result).toBe(false);
});
it("tests for item does exist when jumpSize is invalid", () => {
const arr1 = [1, 3, 5, 7, 8, 9, 40, 100, 200];
const result = jumpSearch(arr1, 100, -20);
expect(result).toBe(true);
});
it("tests for item does not exist when jumpSize is invalid", () => {
const arr1 = [1, 3, 5, 7, 8, 9, 40, 100, 200];
const result = jumpSearch(arr1, 300, -20);
expect(result).toBe(false);
});
});