Thanks to visit codestin.com
Credit goes to github.com

Skip to content
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
56 changes: 56 additions & 0 deletions src/searching/jump-search.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
(function(exports) {
'use strict';
/**
* Searches for specific element in a given array using
* the jump search algorithm.<br><br>
* Time complexity: O(log N).
*
* @example
*
* var search = require('path-to-algorithms/src/searching/'+
* 'jump-search').jumpSearch;
* console.log(search([1, 2, 3, 4, 5], 4)); // 3
*
* @public
* @module searching/jumpsearch
* @param {Array} sortedArray Input array.
* @param {Number} seekIndex of the element which index should be found.
* @returns {Number} Index of the element or -1 if not found.
*/
function jumpSearch(sortedArray, seekIndex) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Index suffix here is a bit misleading.

// exit if array empty
const arrayLength = sortedArray.length;
if (!arrayLength) {
return -1;
}

// set jumpSize
const jumpSize = Math.floor(Math.sqrt(arrayLength));

let blockStart = 0;
let blockEnd = jumpSize;

while (seekIndex > sortedArray[Math.min(blockEnd, arrayLength) - 1]) {
blockStart = blockEnd;
blockEnd += jumpSize;

// if out of array bounds exit
if (blockStart > arrayLength) {
return -1;
}
}

let currentIndex = blockStart;
while (currentIndex < Math.min(blockEnd, arrayLength)) {
if (sortedArray[currentIndex] === seekIndex) {
return currentIndex;
}

currentIndex += 1;
}

return -1;
}

exports.jumpSearch = jumpSearch;
})(typeof window === 'undefined' ? module.exports : window);
21 changes: 21 additions & 0 deletions test/searching/jump-search.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
var jumpSearch = require('../../src/searching/jump-search').jumpSearch;

describe('Jump search', function() {
'use strict';

it('should find the element at position 0 ', function() {
expect(jumpSearch([1, 2, 3, 4, 6, 8], 1)).toBe(0);
});

it('should find the element at position 4 ', function() {
expect(jumpSearch([1, 2, 3, 4, 6, 8], 6)).toBe(4);
});

it('should return -1 ', function() {
expect(jumpSearch([1, 2, 3, 4, 6, 8], 10)).toBe(-1);
});

it('should return -1 ', function() {
expect(jumpSearch([], 10)).toBe(-1);
});
});