forked from sPredictorX1708/Ultimate-Java-Resources
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJump_Search.java
More file actions
21 lines (18 loc) · 911 Bytes
/
Jump_Search.java
File metadata and controls
21 lines (18 loc) · 911 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static int jumpSearch(int[] arrayToSearch, int element) {
int blockSize = (int) Math.floor(Math.sqrt(arrayToSearch.length));
int currentLastIndex = blockSize-1;
// Jump to next block as long as target element is > currentLastIndex
// and the array end has not been reached
while (currentLastIndex < arrayToSearch.length && element > arrayToSearch[currentLastIndex]) {
currentLastIndex += blockSize;
}
// Find accurate position of target element using Linear Search
for (int currentSearchIndex = currentLastIndex - blockSize + 1;
currentSearchIndex <= currentLastIndex && currentSearchIndex < arrayToSearch.length; currentSearchIndex++) {
if (element == arrayToSearch[currentSearchIndex]) {
return currentSearchIndex;
}
}
// Target element not found. Return negative integer as element position.
return -1;
}