






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 # 27 Prof. Lyn Turbak December 6, 2004 Wellesley College
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)
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?