Jump search in Java Print comparisons
If you have an array of size NN, how many comparisons do you need to perform to find each element of this array using jump search?
You are given a number NN. You should output NN number of comparisons you need to perform if the element you search for happens to be in this place.
Sample Input 1:
11
Sample Output 1:
1 4 3 2 5 4 3 6 5 4 5
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
final int n = new Scanner(System.in).nextInt();
final int jump = (int) Math.sqrt(n);
final int tail = (n - 1) % jump;
final int body = n - tail;
for (int i = 0; i < n; i++) {
int x = 1 + i / jump;
final int back = i % jump;
if (back > 0) {
x += jump - back + 1;
}
if (i >= body) {
x -= jump - tail;
}
System.out.print(x + " ");
}
}
}

浙公网安备 33010602011771号