Skip to content

Commit 89a050f

Browse files
author
Fahham29
committed
Add Jump Search algorithm in Java
1 parent 2f2a32b commit 89a050f

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/search/JumpSearch.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package search;
2+
3+
public class JumpSearch {
4+
5+
public static int jumpSearch(int[] arr, int target) {
6+
int n = arr.length;
7+
int step = (int) Math.floor(Math.sqrt(n));
8+
int prev = 0;
9+
10+
while (arr[Math.min(step, n)-1] < target) {
11+
prev = step;
12+
step += Math.floor(Math.sqrt(n));
13+
if (prev >= n)
14+
return -1;
15+
}
16+
17+
for (int i = prev; i < Math.min(step, n); i++) {
18+
if (arr[i] == target)
19+
return i;
20+
}
21+
22+
return -1;
23+
}
24+
25+
public static void main(String[] args) {
26+
int[] arr = {1, 3, 5, 7, 9, 12, 17, 21, 25};
27+
int target = 12;
28+
int index = jumpSearch(arr, target);
29+
System.out.println("Found at index: " + index);
30+
}
31+
}

0 commit comments

Comments
 (0)