可以使用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中。ArrayList元素使用Collections.sort()进行排序。演示这的代码片段如下-
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()查找LinkedList中的元素“ Martha”和“ Amy”是否可用。演示这的代码片段如下-
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);