CSE 250 September 29 – October 3, 2008

advertisement
CSE 250
September 29 – October 3, 2008
ANNOUNCEMENTS
Homework 4 due 10/5
 Project 1 posted for 10/6
 Exam 2 10/8
 No classes meet 10/9
 Project 1 due 10/26

HEAPS / PRIORITY QUEUES
Heaps store elements so that the “next” element
to be deleted is at the root.
 Typically, the “next” is either the minimum
element or the maximum element, so we refer to
a min heap or a max heap, but they are
fundamentally similar

HEAP PROPERTIES

Heap order property



For every node x, the key in the parent of x is smaller
than (or equal to) the key in x.
For all heap operations this must be maintained.
Given that property, we can see that a heap is
some sort of tree. Our first heap will be a binary
heap, so it will be a binary tree that is complete.
That is every level of the tree is filled (has all
nodes possible) from left to right. Only when one
level is full can nodes at a new level be inserted.
POSSIBLE IMPLEMENTATIONS (NAÏVE)

Linked list
Insert at end (simple and efficient)
 When deleting, find minimum element and delete
(simple but O(n) )
 Furthermore, we really thought it should be a tree


Binary Search Tree
Insert and find min and delete would be O(log n)
assuming a balanced tree
 We know that we really can’t safely assume balance

HEAP IMPLEMENTATION (BETTER IDEA)
Use a simple binary tree actually stored on an
array (the fact that is complete makes this easy
to do and not prone to “empty” spots in the
array).
 When implementing a tree on an array, we
remember the following:

Root is stored at index 1
 For the ith element:

The left child of i is at 2i
 The right child of i is at 2i + 1
 The parent of i is at floor(i/2)

HEAP OPERATIONS
Insert: First put element in next available leaf
spot. Then, go up the heap from that point,
swapping child with parent if the parent is
greater than the child.
 Delete: (always root) Put right-most leaf in last
level at the root, then walk down the heap,
swapping the node at the root with the smaller of
the two children.

HEAP CODE

We created some perhaps not totally correct C++
code for the heap implementation that is stored
with the rest of the code in
/projects/CSE250/Fall2008
HUFFMAN TREES
Encoding of data for compression
 Creates a prefix code
 Uses character/frequency records to create a tree
 Tree is used for encoding and decoding the files

ALGORITHM
Start with a list of character-frequency pairs
sorted in ascending order
 Take the first two elements in this list and form a
tree where the frequency stored at the root of this
new tree is the sum of the frequencies of its two
subtrees
 Insert this new tree in proper place in list
mentioned above
 Repeat taking elements two at a time until the
tree is completely formed.

Download