可以使用java.util.Arrays.binarySearch()方法实现对长数组的二进制搜索。如果所需的长元素在数组中可用,则此方法返回其索引,否则返回(-(插入点)-1),其中插入点是元素将在数组中插入的位置。
演示此的程序如下所示-
示例import java.util.Arrays;
public class Demo {
public static void main(String[] args) {
long long_arr[] = { 250L, 500L, 175L, 90L, 415L };
Arrays.sort(long_arr);
System.out.print("The sorted array is: ");
for (long i : long_arr) {
System.out.print(i + " ");
}
System.out.println();
int index1 = Arrays.binarySearch(long_arr, 415L);
System.out.println("The long value 415 is at index " + index1);
int index2 = Arrays.binarySearch(long_arr, 50L);
System.out.println("The long value 50 is at index " + index2);
}
}
输出结果The sorted array is: 90 175 250 415 500
The long value 415 is at index 3
The long value 50 is at index -1
现在让我们了解上面的程序。
长数组long_arr []被定义,然后使用Arrays.sort()进行排序。然后使用for循环打印排序后的数组。演示这的代码片段如下-long long_arr[] = { 250L, 500L, 175L, 90L, 415L };
Arrays.sort(long_arr);
System.out.print("The sorted array is: ");
for (long i : long_arr) {
System.out.print(i + " ");
}
System.out.println();
方法Arrays.binarySearch()用于查找元素415和50的索引。由于415在数组中,因此将显示其索引。另外,数组中也不存在50,因此显示根据(-(插入点)-1)的值。演示这的代码片段如下-int index1 = Arrays.binarySearch(long_arr, 415L);
System.out.println("The long value 415 is at index " + index1);
int index2 = Arrays.binarySearch(long_arr, 50L);
System.out.println("The long value 50 is at index " + index2);