Skip to content

Commit

Permalink
Feature: Jump Search (#57)
Browse files Browse the repository at this point in the history
* feat: jump search

* more test to pass CI/CD
  • Loading branch information
gautam678 authored and nas5w committed Oct 7, 2019
1 parent 88d62cc commit 3b9e2c7
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
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);
});
});

0 comments on commit 3b9e2c7

Please sign in to comment.