JavaAlgorithms/Searches/JumpSearch.java

41 lines
1.1 KiB
Java
Raw Normal View History

2019-10-29 11:34:19 +08:00
package Searches;
public class JumpSearch implements SearchAlgorithm {
2020-10-24 18:23:28 +08:00
public static void main(String[] args) {
JumpSearch jumpSearch = new JumpSearch();
Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int i = 0; i < array.length; i++) {
assert jumpSearch.find(array, i) == i;
2019-10-29 11:34:19 +08:00
}
2020-10-24 18:23:28 +08:00
assert jumpSearch.find(array, -1) == -1;
assert jumpSearch.find(array, 11) == -1;
}
2019-10-29 11:34:19 +08:00
2020-10-24 18:23:28 +08:00
/**
* Jump Search algorithm implements
*
* @param array the array contains elements
* @param key to be searched
* @return index of {@code key} if found, otherwise <tt>-1</tt>
*/
@Override
public <T extends Comparable<T>> int find(T[] array, T key) {
int length = array.length; /* length of array */
int blockSize = (int) Math.sqrt(length); /* block size to be jumped */
2019-10-29 11:34:19 +08:00
2020-10-24 18:23:28 +08:00
int limit = blockSize;
while (key.compareTo(array[limit]) > 0 && limit < array.length - 1) {
limit = Math.min(limit + blockSize, array.length - 1);
}
2019-10-29 11:34:19 +08:00
2020-10-24 18:23:28 +08:00
for (int i = limit - blockSize; i <= limit; i++) {
if (array[i] == key) {
2020-10-24 18:31:42 +08:00
/* execute linear search */
2020-10-24 18:23:28 +08:00
return i;
}
2019-10-29 11:34:19 +08:00
}
2020-10-24 18:23:28 +08:00
return -1; /* not found */
}
2019-10-29 11:34:19 +08:00
}