Java分块查找是一种查找算法,用于在数组或其他有序的数据结构中查找特定的元素。下面是一个示例代码:
public class BlockSearch {
public static void main(String[] args) {
int[] arr = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int blockSize = 3;
int searchElement = 14;
int blockIndex = searchElement / blockSize;
int start = blockIndex * blockSize;
int end = start + blockSize - 1;
while (start <= end && arr[start] <= searchElement && arr[end] >= searchElement) {
if (arr[start] == searchElement) {
System.out.println("Element found at index " + start);
return;
}
if (arr[end] == searchElement) {
System.out.println("Element found at index " + end);
return;
}
start++;
end--;
}
System.out.println("Element not found in the array");
}
}
在上面的代码中,我们首先将数组分成若干个块,每个块的大小由blockSize
变量指定。然后我们计算出要搜索的元素所在的块的索引,并将搜索范围限制在该块内。最后,我们使用双指针查找法在该块内查找元素。如果找到了要查找的元素,就输出它的索引,否则输出“元素不存在”的消息。