使用 Collections.binarySearch 在 Java 中执行二分查找
可以使用方法 java.util.Collections.binarySearch() 在 Java 中执行二分查找。此方法需要两个参数,即要执行二分查找的列表和要搜索的元素。如果该元素在列表中,则返回该元素的索引;如果该元素不在列表中,则返回 -1。
演示此方法的程序如下所示:
示例
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Demo {
public static void main(String args[]) {
List aList = new ArrayList();
aList.add("James");
aList.add("George");
aList.add("Bruce");
aList.add("Susan");
aList.add("Martha");
Collections.sort(aList);
System.out.println("The sorted ArrayList is: " + aList);
int index = Collections.binarySearch(aList, "Martha");
System.out.println("Element Martha is at index: " + index);
index = Collections.binarySearch(aList, "Amy");
System.out.println("Element Amy is at index: " + index);
}
}上述程序的输出如下所示:
The sorted ArrayList is: [Bruce, George, James, Martha, Susan] Element Martha is at index: 3 Element Amy is at index: -1
现在让我们了解上述程序。
创建 ArrayList aList。然后使用 ArrayList.add() 将元素添加到 ArrayList 中。使用 Collections.sort() 对 ArrayList 元素进行排序。演示此方法的代码片段如下所示:
List aList = new ArrayList();
aList.add("James");
aList.add("George");
aList.add("Bruce");
aList.add("Susan");
aList.add("Martha");
Collections.sort(aList);显示排序后的 ArrayList,然后使用 Collections.binarySearch() 查找元素“Martha”和“Amy”是否在 LinkedList 中。演示此方法的代码片段如下所示:
System.out.println("The sorted ArrayList is: " + aList);
int index = Collections.binarySearch(aList, "Martha");
System.out.println("Element Martha is at index: " + index);
index = Collections.binarySearch(aList, "Amy");
System.out.println("Element Amy is at index: " + index);
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP