Jump search in Java Count comparisons
Count how many comparisons you need to do to determine the index of the element, or to determine that this element is not in the array.
You need to use the jump search algorithm described in the theory.
The first line contains the length of an input array, the second one consists of array elements, the last one has the target value.
Sample Input 1:
10
0 1 2 3 4 5 6 7 8 9
0
Sample Output 1:
1
Sample Input 2:
10
0 1 2 3 4 5 6 7 8 9
3
Sample Output 2:
2
Sample Input 3:
10
0 1 2 3 4 5 6 7 8 9
5
Sample Output 3:
4
Sample Input 4:
9
0 1 2 3 4 5 7 8 9
6
Sample Output 4:
4
import java.util.*;
import java.lang.Math;
public class Main {
public static int jumpSearch(int[] array, int target, int count) {
int left = 0;
int right = 0;
int jump = (int) Math.sqrt(array.length);
if (array[0] == target) {
return count;
}
while (right < array.length - 1) {
right = Math.min(array.length - 1, right + jump);
count++;
if (array[right] == target) {
return count;
} else if (array[right] > target) {
break;
}
left = right;
}
for (int i = right; i > left + 1; i--) {
if (array[i] <= target) {
break;
}
count++;
}
return count;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = input.nextInt();
}
int val = input.nextInt();
System.out.println(jumpSearch(arr, val, 1));
}
}

浙公网安备 33010602011771号