Skip to content

Commit b45ed38

Browse files
committed
Added JumpSearch Algorithm in Searching folder.
1 parent 280509f commit b45ed38

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Searching/JumpSearch.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class JumpSearch {
2+
public static int jumpSearch(int[] arr, int x){
3+
int n = arr.length;
4+
5+
// Finding block size to be jumped
6+
int step = (int)Math.floor(Math.sqrt(n));
7+
8+
// Finding the block where element is
9+
// present (if it is present)
10+
int prev = 0;
11+
while (arr[Math.min(step, n)-1] < x){
12+
prev = step;
13+
step += (int)Math.floor(Math.sqrt(n));
14+
if (prev >= n)
15+
return -1;
16+
}
17+
18+
// Doing a linear search for x in block
19+
// beginning with prev.
20+
while (arr[prev] < x){
21+
prev++;
22+
23+
// If we reached next block or end of
24+
// array, element is not present.
25+
if (prev == Math.min(step, n))
26+
return -1;
27+
}
28+
29+
// If element is found
30+
if (arr[prev] == x)
31+
return prev;
32+
33+
return -1;
34+
}
35+
36+
// Driver program to test function
37+
public static void main(String [ ] args){
38+
int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21,
39+
34, 55, 89, 144, 233, 377, 610};
40+
int x = 55;
41+
42+
// Find the index of 'x' using Jump Search
43+
int index = jumpSearch(arr, x);
44+
45+
// Print the index where 'x' is located
46+
System.out.println("\nNumber " + x + " is at index " + index);
47+
}
48+
}

0 commit comments

Comments
 (0)