使用 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);
廣告