Skip to content

Instantly share code, notes, and snippets.

@Nilesh-Saini-09
Created June 20, 2022 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nilesh-Saini-09/c64b2c285cec75f9bcb0f3522e1efc0f to your computer and use it in GitHub Desktop.
Save Nilesh-Saini-09/c64b2c285cec75f9bcb0f3522e1efc0f to your computer and use it in GitHub Desktop.
jumpSearch.js
// ES6 Arrow Function
const jumpSearch = (arr, x) => {
let n = arr.length;
// block size
let block = Math.floor(Math.sqrt(n));
let prev = 0;
// Finding the block
while (arr[Math.min(block, n) - 1] < x) {
prev = block;
block += Math.sqrt(n);
if (prev >= n) return -1;
}
// Linear Search in the block
while (arr[prev] < x) {
prev++;
if (prev == Math.min(block, n)) return -1;
}
if (arr[prev] == x) return prev;
return -1;
}
// let testArray = [1, 2, 3, 4, 5, 6];
// let x = 3;
// jumpSearch(testArray, x);
// output => 2;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment