Skip to content

Commit e0ea61b

Browse files
committed
Added jump search implementation
Fixes TheAlgorithms#96
1 parent 8917e41 commit e0ea61b

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Searches/JumpSearch.java

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

0 commit comments

Comments
 (0)