









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










CS230 Data Structures Handout # 24 Prof. Lyn Turbak Monday, December 9, 2002 Wellesley College
This is a revised version of the preliminary handout distributed on Tue. Dec. 3.
The Many Meanings of Heap
The word heap has several different common meanings in computer science:
Here we shall focus on interpretation #2, though #1 shall be implied in the term heapsort.
Heapsort
Heapsort is a sorting algorithm based on priority queues. Here is a generic form based on a max priority queue:
// Modify vector to contain sorted elements from low to hi public static void heapSortMax (Vector v) { // Create a max pq MaxPQ pq = new MaxPQZZZ(); // Any MaxPQ implementation will do. // Insert all elements from vector into max pq for (int i = 0; i < v.size(); i++) { pq.enq(v.get(i)); } // Store all elements in sorted order from max pq into vector for (int i = v.size() - 1; i >= 0; i--) { // Must go from highest index down v.set(i, pq.deq()); } }
Notes:
Efficiency of Max PQ Operations
What is the worst-case asymptotic running times of the following max pq operations for the specified implementations? Assume enq(), deq(), and first() are invoked on an n-element heap, and heapSort() is invoked on an n-element vector.
Implementation enq() deq() first() heapSort() Vector sorted low to high Vector sorted high to low Binary search tree Complete heap (this handout) Leftist heap (this handout)
The Heap Condition
For meaning #2 of heap, a binary tree is a max heap if it satisfies the following condition at every node in the tree.
Max Heap Condition: The value of a node is ≥ the values of all values in both subtrees.
Similarly, a min heap satisfies at every node a min heap condition in which the node value is ≤ the values of all values in both subtrees.
Max Heap Example
Consider the following integer tree T:
Tree Max heap? T left(T) right(T) left(left(T)) right(left(T)) left(right(T)) right(right(T))
Complete Trees
An n-element binary tree is complete if the set of binary addresses of its nodes is the n-element set { 1 ,... , n}.
Example: Reconsider the tree T:
Tree Complete? T left(T) right(T) left(left(T)) right(left(T)) left(right(T)) right(right(T)) left(left(left(T)))
Note: An n-element binary tree is full if it is a complete tree of height h with 2h^ − 1 nodes. Which subtrees of T are full?
What’s So Great About Complete Trees?
Complete trees have two important features:
4 2
3 4 1 5
can be represented as the array
Note: In languages with 0-based array indexing, the index is one less than the binary address.
Address Arithmetic For Complete Trees
Operation Name Defn. (1-based indexing) Defn. (0-based indexing) left address laddr(index) 2 * index (2 * index) + 1 right address raddr(index) (2 * index) + 1 (2 * index) + 2 parent address paddr(index) index div 2 (index - 1) div 2
Complete Heaps
A complete (max) heap is a binary tree that is both complete and a max heap.
Example: Below are some sample complete max heaps containing the letters A L G O R I T H M S. A letter later in the alphabet is considered greater than a letter earlier in the alphabet. These are just some of the many possible complete heaps possible with this set of elements.
T
S
M
A H
Complete Heap Enqueuing
We can enqueue an element x onto a complete heap in time proportional to its height by:
Step #1 takes constant time and step #2 takes worst-case time proportional to the height of the tree, which is Θ(log(n)).
Complete Heap Enqueuing Code
Here is Java code for enqueuing onto a complete heap represented as a vector instance variable elts and comparator comp.
public void enq (Object x) { elts.add(x); // Add x at next binary address bubbleUp(elts.size() - 1); // Bubble up from last binary address }
public void bubbleUp (int addr) { while ((addr > 0) && greaterThan(addr, paddr(addr))) { swap(addr, paddr(addr)); addr = paddr(addr); } }
public boolean greaterThan (int addr1, int addr2) { return comp.compare(elts.get(addr1), elts.get(addr2)) > 0; }
public void swap (int addr1, int addr2) { Object temp = elts.get(addr1); elts.set(addr1, elts.get(addr2)); elts.set(addr2, temp); }
Complete Heap Dequeuing
We can dequeue the next element from a complete heap in time proportional to its height by:
Steps #1, #2, #4 take constant time and step #3 takes worst-case time proportional to the height of the tree, which is Θ(log(n)).
Complete Heap Dequeuing Example
We will use the dequeuing algorithm specified above to dequeue all the elements from the complete heap that resulted from the enqueuing process:
delete → T
bubbleDown → L
bubbleDown → L
delete → S
bubbleDown → H
bubbleDown → H
delete → R
bubbleDown → A
bubbleDown → A
delete → O
bubbleDown → H
bubbleDown → H
delete → M
bubbleDown → G
bubbleDown → G
delete → L
bubbleDown → G
delete → I
bubbleDown → A
delete → H
delete → G A^
delete → A
Building a Complete Heap From a Vector
It is often necessary to build a complete heap from a given collection of objects, such as a vector, array, list, etc. For concreteness, we will focus on building a complete heap from a vector. What’s an efficient way to do this?
A Θ(n · log(n)) approach An obvious approach is to simply enqueue all the elements from the vector one-by-one into an initially empty complete heap. Here’s the code for such an approach:
public static MaxPQ fromVector (Vector v) { MaxPQ pq = new MaxPQCompleteHeap(); Enumeration xs = v.elements(); while (xs.hasMoreElements()) { pq.enq(xs.nextElement()); } return pq; }
You should convince yourself that this takes time Θ(n · log(n)) for an n-element vector.
A Θ(n) approach An alternative approach is to use a copy of the given vector as the vector representing the complete heap, and to “bubble down” elements starting at the next to last row of the heap and working up to the top row of the heap. This ordering guarantees that by the time the bubbling down process is invoked at a node, both subtrees are already guaranteed to be heaps. So after the final “bubble down” is performed at the root of the tree, the tree is guaranteed to be a heap. Here is the code for this approach:
public static MaxPQ fromVector (Vector v) { MaxPQCompleteHeap pq = new MaxPQCompleteHeap(); pq.elts = (Vector) v.clone(); // Note: (v.size() - 2) is the largest index of an // element in the next to last level of the tree. for (int i = ((v.size() - 2) / 2); i >= 0; i--) { pq.bubbleDown(i); } return pq; }
It turns out that the running time of this algorithm is Θ(n), which is asymptotically faster than the “obvious” algorithm explored above.
Heapsort Revisited
When using heapSort to sort a vector v, it is possible to use v itself for the elements of the compelete heap rather than using a copy of v. This leads to a version of heapSort that is in-place, which means it uses only constant extra storage space in addition to the vector being sorted. This idea will only work with max complete heaps. Why won’t it work for min complete heaps?
Leftist Trees
Let the rank^1 of a binary tree be the length of its right spine – i.e., the length of the rightmost path from the root to a leaf.
Example: Nodes in the following tree are annotated with their ranks:
Call a binary tree leftist iff it satisfies the following leftist condition for every subtree t of the tree: rank(left(t)) ≥ rank(right(t)) In the above example, the subtrees rooted at T and S (and, necessarily, all of their subtrees) are leftist, but the subtree rooted at M is not lefist. It is not difficult to show the following fact: Let n be the number of nodes in a leftist tree and r be its rank. Then r ≤ lg(n + 1). It turns out that the time taken to enqueue an element onto, dequeue and element from, and merge a leftist tree with a leftist tree depend on the length of its right spine and so are proportional to its rank r. By the above fact, these operations on leftist trees are guaranteed to take only logarithmic time in the worst case.
Leftist Heaps
A leftist (max) heap is simply a binary tree that is both leftist and a (max) heap. Leftist min heaps are defined similarly.
Example: The following is one of the many leftist max heaps for the letters in the word ALGORITHMS. To save on space, explicit leaves have been omitted.
(^1) The term “rank” is often used as a name for some relevant property of a data structure. Exactly which property it refers to depends on the particular data structure and what is trying to be proven.
Merging Example Below we show the merging of two leftist heaps: one that contains the letters A L G O R and one that contains the letters I T H M S.
merge
R 2
L 2
G 1 A 1
T merge
M 1 R 2
L 2
G 1 A 1
R merge
M 1 O 1
(^0) O merge
0 M 1
Note how the leftist condition guarantees that the trees are skewed toward the left, which means that the right spine tends to be short. In the above example, the result of merging two trees with a right spine length of 2 yields another tree with a right spine length of 2! Interestingly, leftist trees are particularly efficient when they are isomorphic to lists along the left spine and are least efficient when they are balanced!
Dequeuing From a Leftist Heap
Other priority queue operations are easy to implement with leftist heaps, often in terms of merge. For example, To dequeue an element from a leftist heap, remember the root value to return later and merge the two subtrees of the root node.
Example: Dequeuing an element from the result of the merge on the previous page returns T and yields the following leftist heap:^2
merge
R 2
L 2
G 1 A 1
Enqueuing Onto a Leftist Heap
To enqueue an element x onto a leftist heap t, merge a single tree containing x with t:
Example: Enqueuing Q onto the result of the previous dequeue step yields the following leftist heap:
merge
Q (^1) S 3
R 2
L 2
G 1 A 1
(^2) The notation ⇒∗ (^) indicates the application of potentially several rewrite steps, whose intermediate results are not shown.