我假設鏈接列表進行排序 - 否則它不能在基於比較算法來完成,因爲你需要它Omega(nlogn)
- 迭代排序的「最高水平」列表中,並且每隔一個節點添加一個「鏈接節點」。
- 重複,直到最高級別只有一個節點。
這個想法是生成一個新的列表,原始大小的一半,它鏈接到原始的每個第二鏈接,然後遞歸調用小列表,直到你到達一個大小爲1的列表
您最後將列出大小爲1,2,4,...,n/2的鏈接。
僞代碼:
makeSkipList(list):
if (list == null || list.next == null): //stop clause - a list of size 1
return
//root is the next level list, which will have n/2 elements.
root <- new link node
root.linkedNode <- list //linked node is linking "down" in the skip list.
root.next <- null //next is linking "right" in the skip list.
lastLinkNode <- root
i <- 1
//we create a link every second element
for each node in list, exlude the first element:
if (i++ %2 == 0): //for every 2nd element, create a link node.
lastLinkNode.next <- new link node
lastLinkNode <- lastLinkNode.next //setting the "down" field to the element in the list
lastLinkNode.linkedNode <- node
lastLinkNode.next <- null
makeSkipList(root) //recursively invoke on the new list, which is of size n/2.
複雜性是因爲算法複雜度可以描述爲T(n) = n + T(n/2)
爲O(n),這樣你可以獲得T(n) = n + n/2 + n/4 + ... -> 2n
這是很容易看到它不能做的更好然後O(n)
,因爲至少你將不得不在原始列表的後半部分添加至少一個節點,並且到達那裏本身是O(n)
請參閱[wiki頁面](http://en.wikipedia.org/wiki/Skip_list),瞭解您提到的隨機算法 – HelloWorld 2012-04-28 19:29:35