使用 Java Collection 在 ArrayList 上執行二叉查詢
為了使用 Java Collection 在 ArrayList 上執行二進位制搜尋,我們要使用 Collections.binarySearch() 方法。
宣告 - java.util.Collections.binarySearch() 方法的宣告如下 -
public static int binarySearch(List list, T key)
以上方法以升序排列的列表返回鍵的位置。如果我們使用比較器 c 對列表進行排序,則 binarySearch() 方法的宣告如下 -
public static int binarySearch(List list, T key, Comparator c)
如果鍵不存在,則返回 ((插入點) + 1) *(-1)。
讓我們看看一個在 ArrayList 上執行 binarySearch() 的程式 -
示例
import java.util.*; public class Example { public static void main (String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(7); int pos = Collections.binarySearch(list, 1); // 1 is present at 0th index System.out.println(pos); pos = Collections.binarySearch(list, 5); /* since 5 is not present and it would be inserted at index 2 the method returns (-1)*() */ System.out.println(pos); } }
輸出
0 -3
廣告