-
-
Save Nilesh-Saini-09/c64b2c285cec75f9bcb0f3522e1efc0f to your computer and use it in GitHub Desktop.
jumpSearch.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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