Java 程序在 long 数组上实现二分查找


可以通过使用 java.util.Arrays.binarySearch() 方法在 long 数组上实现二分查找。此方法返回所需的 long 元素的索引(如果它在数组中可用),否则返回 (-(插放点) - 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 数组 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);

更新于: 2020 年 6 月 25 日

201 次观看

开启你的 职业

完成课程并获得认证

入门
广告
© . All rights reserved.