0
此示例演示如何確定元素應插入到排序列表中的索引。雖然binarySearch()用於定位存在的元素,但它也可用於確定不存在的元素的插入索引。算法的漸近分析:如何在時間O(k log k + n)中插入k個新元素到大小爲n的排序列表中
// Create a list with an ordered list of items
List sortedList = new LinkedList();
sortedList.addAll(Arrays.asList(new String[]{"ant", "bat", "cat", "dog"}));
// Search for the non-existent item int index = Collections.binarySearch(sortedList, "cow");
// -4 // Add the non-existent item to the list
if (index < 0) { sortedList.add(-index-1, "cow"); }
我怎麼不能插入時間O(k日誌k + n)的元素。 k是列表的數量。 n是所有列表中元素的總數(n = n1 + n2 + ... + nk)。
解釋算法的漸近分析?
@MSN:如果沒有OP的說明,請停止添加作業標籤。 – 2010-11-19 17:31:02
@Moron,啊,我的壞。鑑於文字,我應該首先google第一段:http://www.exampledepot.com/egs/java.util/coll_InsertInList.html – MSN 2010-11-19 17:43:17
不熟悉java LinkedList,它真的支持二進制搜索嗎? – Axn 2010-11-19 19:19:52