Docsity

Heaps - Data Structures - Lecture Handout #37 | CS 230, Study notes of Data Structures and Algorithms

Toggle sidebar
bg1
CS230 Data Structures Handout # 37
Prof. Lyn Turbak Thursday, April 26, 2007
Wellesley College
Heaps
The Many Meanings of Heap
The word heap has several different common meanings in computer science:
1. It is used as a synonym for an abstract priority queue.
2. It is used to refer to a particular class of concrete implementations for a priority queue. In
this interpretation, some priority queues are heaps and some are not, which is at odds with
meaning #1.
3. In a very different interpretation, heap is commonly used to refer to the region of memory
used for storing entities whose lifetime exceeds that of the execution frame in which they were
created (a.k.a. heap = Object Land). This is in contrast to the stack, which is the region of
memory used for storing entities whose lifetime is less than or equal to that of the execution
frame in which they were created (a.k.a. stack = Execution Land).
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 implementation:
// Modify vector to contain elements sorted from low to high
public static <T> void heapSort (Vector<T> v, Comparable<T> comp) {
// (1) Create an empty priority queue (any implementation will do)
PQueue pq = new PQueueZZZ(comp);
// (2) Insert all elements from vector into priority queue:
for (int i = 0; i < v.size(); i++) {
pq.enq(v.get(i));
}
// Store all elements in sorted order from priority queue into vector
for (int i = v.size()-1; i >= 0; i--) { // must go from highest index down!
v.set(i, pq.deq());
}
}
Notes:
•We can supply any Comparator<T> to compare elements of type T. By the PQueue contract,
supplying null for the comparator will use the Comparable<T> compareTo() method for
comparisons (if type Thas one).
•Later, we shall see that heapsort is particularly efficient if a certain implementation of priority
queues is used. Some people reserve the term heapsort for this particularly efficient version.
1
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Heaps - Data Structures - Lecture Handout #37 | CS 230 and more Study notes Data Structures and Algorithms in PDF only on Docsity!

CS230 Data Structures Handout # 37 Prof. Lyn Turbak Thursday, April 26, 2007 Wellesley College

Heaps

The Many Meanings of Heap

The word heap has several different common meanings in computer science:

  1. It is used as a synonym for an abstract priority queue.
  2. It is used to refer to a particular class of concrete implementations for a priority queue. In this interpretation, some priority queues are heaps and some are not, which is at odds with meaning #1.
  3. In a very different interpretation, heap is commonly used to refer to the region of memory used for storing entities whose lifetime exceeds that of the execution frame in which they were created (a.k.a. heap = Object Land). This is in contrast to the stack, which is the region of memory used for storing entities whose lifetime is less than or equal to that of the execution frame in which they were created (a.k.a. stack = Execution Land).

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 implementation:

// Modify vector to contain elements sorted from low to high public static void heapSort (Vector v, Comparable comp) { // (1) Create an empty priority queue (any implementation will do) PQueue pq = new PQueueZZZ(comp); // (2) Insert all elements from vector into priority queue: for (int i = 0; i < v.size(); i++) { pq.enq(v.get(i)); } // Store all elements in sorted order from priority queue into vector for (int i = v.size()-1; i >= 0; i--) { // must go from highest index down! v.set(i, pq.deq()); } }

Notes:

  • We can supply any Comparator to compare elements of type T. By the PQueue contract, supplying null for the comparator will use the Comparable compareTo() method for comparisons (if type T has one).
  • Later, we shall see that heapsort is particularly efficient if a certain implementation of priority queues is used. Some people reserve the term heapsort for this particularly efficient version.

Efficiency of Max PQ Operations

What is the worst-case asymptotic running times of the following priority queue 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() front() 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 nodes 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 string tree T:

F

E

D

C A

F

B

D

A B

B

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:

  1. The height of an n-node complete tree is Θ(log(n)) in the worst case.
  2. Because the binary addresses cover the range 1 to n, complete trees are easily represented as arrays/vectors. E.g., in languages with 1-based array indexing: E 1

D 2

C 4 A 5

F 3

B 6

can be represented as the array

E D F C A B

Note: In languages with 0-based array indexing (e.g., Java and C), the index is one less than the binary address:

E D F C A B

Address Arithmetic For Complete Trees

Operation Name Defn. (1-based indexing) Defn. (0-based indexing) left address laddr(index) 2index (2index)+ right address raddr(index) (2index)+1 (2index)+ parent address paddr(index) index/2 (index-1)/

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. These are just some of the many possible complete heaps possible with this set of elements.

T

S

M

A H

O

L

R

G I

T

R

M

A H

O

L

S

G I

T

R

O

A H

M

L

S

G I

T

R

M

A G

O

H

S

I L

T

M

L

H I

G

A

S

R O

T

S

R

O M

L

I

H

G A

Complete Heap Enqueuing

We can enqueue an element x into a complete heap in time proportional to its height by:

  1. inserting x in the next “free” complete tree slot. This maintains completeness of the tree but can violate the heap condition.
  2. “trickling x up” towards the root until the heap condition is restored. The result is a complete heap with one more element.

Step #1 takes constant time and step #2 takes worst-case time proportional to the height of the tree, which is Θ(log(n)).

Java Code for Complete Heap Enqueuing

Here is Java code for enqueuing into a complete heap represented as a vector instance variable elts and comparator comp.

public void enq (T x) { elts.add(x); // Add x at next binary address trickleUp(elts.size() - 1); // Trickle up from last binary address }

private void trickleUp (int addr) { while ((addr > 0) && greaterThan(addr, paddr(addr))) { swap(addr, paddr(addr)); addr = paddr(addr); } }

private boolean greaterThan (int addr1, int addr2) { return compare(elts.get(addr1), elts.get(addr2)) > 0; }

private void swap (int addr1, int addr2) { T 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:

  1. remembering the top node value first (which will be returned later);
  2. moving the value last from the last complete tree slot into the top node. This maintains completeness of the tree but can violate the heap condition;
  3. “trickling last down” by swapping it with the larger of its two children (if one is greater than last) until the heap condition is restored. The result is a complete heap with one less element;
  4. returning the remembered value first.

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:

T

S

M

A H

O

L

R

G I

delete → T

L

S

M

A H

O

R

G I

trickleDown → L

S

L

M

A H

O

R

G I

trickleDown → L

S

O

M

A H

L

R

G I

delete → S

H

O

M

A

L

R

G I

trickleDown → H

R

O

M

A

L

H

G I

trickleDown → H

R

O

M

A

L

I

G H

delete → R

A

O

M L

I

G H

trickleDown → A

O

A

M L

I

G H

trickleDown → A

O

M

A L

I

G H

delete → O

H

M

A L

I

G

trickleDown → H

M

H

A L

I

G

trickleDown → H

M

L

A H

I

G

delete → M

G

L

A H

I

trickleDown → G

L

G

A H

I

trickleDown → G

L

H

A G

I

delete → L

G

H

A

I

trickleDown → G

I

H

A

G

delete → I

A

H G

trickleDown → A

H

A G

delete → H

G

A

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 PQueueCompleteHeap fromVectorInefficient (Vector v) { PQueueCompleteHeap pq = new PQueueCompleteHeap(); for (int i = 0; i < v.size(); i++) { pq.enq(v.get(i)); } 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 “trickle 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 trickling-down process is invoked at a node, both subtrees are already guaranteed to be heaps. So after the final “trickle 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 PQueueCompleteHeap fromVector (Vector v, Comparator comp) { PQueueCompleteHeap pq = new PQueueCompleteHeap(comp); pq.elts = (Vector) v.clone(); pq.buildHeap(); return pq; }

private void buildHeap () { // Note: (v.size() - 2) is the largest index of an // element in the next to last level of the tree. for (int i = ((elts.size() - 2) / 2); i >= 0; i--) { trickleDown(i); } }

It turns out that the running time of this algorithm is Θ(n), which is asymptotically faster than the “obvious” algorithm explored above. See CS231 for the details. Sometimes we want to re-use the supplied vector for holding the elements of the priority queue: public static PQueueCompleteHeap fromVectorShared (Vector v, Comparator comp) { PQueueCompleteHeap pq = new PQueueCompleteHeap(comp); pq.elts = v; pq.buildHeap(); return pq; }

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.

public static void heapSortEfficient (Vector v, Comparator comp) { PQueueCompleteHeap pq = fromVectorShared(v, comp); for (int i = v.size()-1; i >= 0; i--) { v.set(i, pq.deq()); } }

This idea will only work with max complete heaps. Why won’t it work for min complete heaps?