Skip to content

Add jumpSearch algorithm #75

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

Closed
wants to merge 3 commits into from
Closed
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
26 changes: 26 additions & 0 deletions src/_Searching_/JumpSearch/JumpSearch.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const { jumpSearch, jumpSearchRecursive } = require('.');

describe('Jump Search', () => {
    const array = [1, 2, 3, 4, 5, 6, 7, 8];
    const jump = 3;
    describe('When element to find is at 1st position ', () => {
        it('Jump search', () => {
          expect(jumpSearch(array, jump, 1)).toEqual(0);
        });
      });
    describe('When element to find is at last position ', () => {
        it('Jump search', () => {
          expect(jumpSearch(array, jump, 7)).toEqual(6);
        });
      });
    describe('When element to find is at random position ', () => {
        it('Jump search', () => {
          expect(jumpSearch(array, jump, 3)).toEqual(2);
        });
      });
    describe('When jump is larger than array', () => {
        it('Jump search', () => {
          expect(jumpSearch(array, 9, 3)).toEqual(2);
        });
      });
});
31 changes: 31 additions & 0 deletions src/_Searching_/JumpSearch/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
function jumpSearch(arr, jump, key) {
// treat jumps larger than array size as linear search
jump = jump > arr.length ? 1 : jump;

let low = 0, high = 0;
for (let i = jump; i < arr.length; i+=jump) {
if(key < arr[i]) {
high = i;
low = i - jump;
break;
}
}

// check if loop has finished without finding key
if(high == 0) {
high = arr.length;
low = high - jump;
}

for(let i = low; i < high; i++) {
if(arr[i] == key) {
// return the index of the key
return i;
}
}
return null;
}

module.exports = {
jumpSearch,
};