Skew heapA skew heap (or self-adjusting heap) is a heap data structure implemented as a binary tree. Skew heaps are advantageous because of their ability to merge more quickly than binary heaps. In contrast with binary heaps, there are no structural constraints, so there is no guarantee that the height of the tree is logarithmic. Only two conditions must be satisfied:
A skew heap is a self-adjusting form of a leftist heap which attempts to maintain balance by unconditionally swapping all nodes in the merge path when merging two heaps. (The merge operation is also used when adding and removing values.) With no structural constraints, it may seem that a skew heap would be horribly inefficient. However, amortized complexity analysis can be used to demonstrate that all operations on a skew heap can be done in O(log n).[1] In fact, with denoting the golden ratio, the exact amortized complexity is known to be logφ n (approximately 1.44 log2 n).[2][3] DefinitionSkew heaps may be described with the following recursive definition:[citation needed][clarification needed]
OperationsMerging two heapsWhen two skew heaps are to be merged, we can use a similar process as the merge of two leftist heaps:
template<class T, class CompareFunction>
SkewNode<T>* CSkewHeap<T, CompareFunction>::Merge(SkewNode<T>* root_1, SkewNode<T>* root_2)
{
SkewNode<T>* firstRoot = root_1;
SkewNode<T>* secondRoot = root_2;
if (firstRoot == NULL)
return secondRoot;
else if (secondRoot == NULL)
return firstRoot;
if (sh_compare->Less(firstRoot->key, secondRoot->key))
{
SkewNode<T>* tempHeap = firstRoot->rightNode;
firstRoot->rightNode = firstRoot->leftNode;
firstRoot->leftNode = Merge(secondRoot, tempHeap);
return firstRoot;
}
else
return Merge(secondRoot, firstRoot);
}
Non-recursive mergingAlternatively, there is a non-recursive approach which is more wordy, and does require some sorting at the outset.
Adding valuesAdding a value to a skew heap is like merging a tree with one node together with the original tree. Removing valuesRemoving the first value in a heap can be accomplished by removing the root and merging its child subtrees. ImplementationIn many functional languages, skew heaps become extremely simple to implement. Here is a complete sample implementation in Haskell. data SkewHeap a = Empty
| Node a (SkewHeap a) (SkewHeap a)
singleton :: Ord a => a -> SkewHeap a
singleton x = Node x Empty Empty
union :: Ord a => SkewHeap a -> SkewHeap a -> SkewHeap a
Empty `union` t2 = t2
t1 `union` Empty = t1
t1@(Node x1 l1 r1) `union` t2@(Node x2 l2 r2)
| x1 <= x2 = Node x1 (t2 `union` r1) l1
| otherwise = Node x2 (t1 `union` r2) l2
insert :: Ord a => a -> SkewHeap a -> SkewHeap a
insert x heap = singleton x `union` heap
extractMin :: Ord a => SkewHeap a -> Maybe (a, SkewHeap a)
extractMin Empty = Nothing
extractMin (Node x l r) = Just (x, l `union` r)
References
External links |
Portal di Ensiklopedia Dunia