Skip to content

Commit 16a215e

Browse files
add jump search algorithm
1 parent cbc1899 commit 16a215e

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Searches/JumpSearch.java

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package Searches;
2+
3+
public class JumpSearch implements SearchAlgorithm {
4+
5+
public static void main(String[] args) {
6+
JumpSearch jumpSearch = new JumpSearch();
7+
Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
8+
for (int i = 0; i < array.length; i++) {
9+
assert jumpSearch.find(array, i) == i;
10+
}
11+
assert jumpSearch.find(array, -1) == -1;
12+
assert jumpSearch.find(array, 11) == -1;
13+
}
14+
15+
/**
16+
* Jump Search algorithm implements
17+
*
18+
* @param array the array contains elements
19+
* @param key to be searched
20+
* @return index of {@code key} if found, otherwise <tt>-1</tt>
21+
*/
22+
@Override
23+
public <T extends Comparable<T>> int find(T[] array, T key) {
24+
int length = array.length; /* length of array */
25+
int blockSize = (int) Math.sqrt(length); /* block size to be jumped */
26+
27+
int limit = blockSize;
28+
while (key.compareTo(array[limit]) > 0 && limit < array.length - 1) {
29+
limit = Math.min(limit + blockSize, array.length - 1);
30+
}
31+
32+
for (int i = limit - blockSize; i <= limit; i++) {
33+
if (array[i] == key) { /* execute linear search */
34+
return i;
35+
}
36+
}
37+
return -1; /* not found */
38+
}
39+
}

0 commit comments

Comments
 (0)