Skip to content

Commit e95a208

Browse files
committed
✨ Jump search added
1 parent 7a06f72 commit e95a208

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

Search/JumpSearch/README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#Run
2+
3+
`node Search/JumpSearch [1,2,3,4] 3 1`
4+
5+
Output:
6+
7+
1. Success - `2 (Index)`
8+
2. Failure - `-1`

Search/JumpSearch/index.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
let arr = process.argv[2].replace("[", "");
2+
arr = arr.replace("]", "");
3+
arr = arr.split(",").map(Number);
4+
const x = Number(process.argv[3]);
5+
const n = Number(process.argv[4]);
6+
// Finding block size to be jumped
7+
step = Math.sqrt(n);
8+
9+
// Finding the block where element is
10+
// present (if it is present)
11+
prev = 0;
12+
while (arr[parseInt(Math.min(step, n) - 1)] < x) {
13+
prev = step;
14+
step += Math.sqrt(n);
15+
if (prev >= n) {
16+
console.log(-1);
17+
return;
18+
}
19+
}
20+
21+
// Doing a linear search for x in
22+
// block beginning with prev.
23+
while (arr[parseInt(prev)] < x) {
24+
prev += 1;
25+
26+
// If we reached next block or end
27+
// of array, element is not present.
28+
if (prev == Math.min(step, n)) {
29+
console.log(-1);
30+
return;
31+
}
32+
}
33+
34+
// If element is found
35+
if (arr[parseInt(prev)] == x) {
36+
console.log(prev);
37+
}

0 commit comments

Comments
 (0)