Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 9fd51ef

Browse files
duffman85mgechev
andauthoredApr 7, 2020
Add jump search algo (mgechev#157)
* Add jump search algo * Update src/searching/jump-search.js Co-authored-by: Minko Gechev <[email protected]>
1 parent 888ad51 commit 9fd51ef

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
 

‎src/searching/jump-search.js

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
(function(exports) {
2+
'use strict';
3+
/**
4+
* Searches for specific element in a given array using
5+
* the jump search algorithm.<br><br>
6+
* Time complexity: O(log N).
7+
*
8+
* @example
9+
*
10+
* var search = require('path-to-algorithms/src/searching/'+
11+
* 'jump-search').jumpSearch;
12+
* console.log(search([1, 2, 3, 4, 5], 4)); // 3
13+
*
14+
* @public
15+
* @module searching/jumpsearch
16+
* @param {Array} sortedArray Input array.
17+
* @param {Number} seekIndex of the element which index should be found.
18+
* @returns {Number} Index of the element or -1 if not found.
19+
*/
20+
function jumpSearch(sortedArray, seekIndex) {
21+
// exit if array empty
22+
const arrayLength = sortedArray.length;
23+
if (!arrayLength) {
24+
return -1;
25+
}
26+
27+
// set jumpSize
28+
const jumpSize = Math.floor(Math.sqrt(arrayLength));
29+
30+
let blockStart = 0;
31+
let blockEnd = jumpSize;
32+
33+
while (seekIndex > sortedArray[Math.min(blockEnd, arrayLength) - 1]) {
34+
blockStart = blockEnd;
35+
blockEnd += jumpSize;
36+
37+
// if out of array bounds exit
38+
if (blockStart > arrayLength) {
39+
return -1;
40+
}
41+
}
42+
43+
let currentIndex = blockStart;
44+
while (currentIndex < Math.min(blockEnd, arrayLength)) {
45+
if (sortedArray[currentIndex] === seekIndex) {
46+
return currentIndex;
47+
}
48+
49+
currentIndex += 1;
50+
}
51+
52+
return -1;
53+
}
54+
55+
exports.jumpSearch = jumpSearch;
56+
})(typeof window === 'undefined' ? module.exports : window);

‎test/searching/jump-search.spec.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
var jumpSearch = require('../../src/searching/jump-search').jumpSearch;
2+
3+
describe('Jump search', function() {
4+
'use strict';
5+
6+
it('should find the element at position 0 ', function() {
7+
expect(jumpSearch([1, 2, 3, 4, 6, 8], 1)).toBe(0);
8+
});
9+
10+
it('should find the element at position 4 ', function() {
11+
expect(jumpSearch([1, 2, 3, 4, 6, 8], 6)).toBe(4);
12+
});
13+
14+
it('should return -1 ', function() {
15+
expect(jumpSearch([1, 2, 3, 4, 6, 8], 10)).toBe(-1);
16+
});
17+
18+
it('should return -1 ', function() {
19+
expect(jumpSearch([], 10)).toBe(-1);
20+
});
21+
});

0 commit comments

Comments
 (0)
Please sign in to comment.