Heaps and Priority Queues Basic idea in this chapter: We prioritize data structures for special purp - PowerPoint PPT Presentation

1 / 114
About This Presentation
Title:

Heaps and Priority Queues Basic idea in this chapter: We prioritize data structures for special purp

Description:

Problem - At the Bank, bust stop. Queue at the counter or bus stop. Give ... small jobs(1page print) may be given priority over large jobs (100pages) ... 1 4 2 ... – PowerPoint PPT presentation

Number of Views:107
Avg rating:3.0/5.0
Slides: 115
Provided by: halukb
Category:

less

Transcript and Presenter's Notes

Title: Heaps and Priority Queues Basic idea in this chapter: We prioritize data structures for special purp


1
Heaps and Priority QueuesBasic idea in this
chapter We prioritize data structures for
special purposes Heap is a kind of tree
structureUse a heaps to implement a priority
queue
Some parts of this slides are the courtesy of
Haluk Bingöl
2
Content
  • Motivation the need for priority queuing ?
    Fair/unfair?
  • Background (queues and tree structures)
  • What is a heap
  • Heap types Leftist, Binomial, d-type, skew
  • Merging two heaps
  • Analysis and implementation details

3
Priority Queue (Heaps)
  • Priority Queue is a data structure allowing at
    least the following two operations
  • insert same like enqueue in nonpriority queues
  • deleteMin is the priority queue equivalent of
    queues dequeu operation (i.e. find and remove
    the minimum element in prioritized queue)
  • Efficient implementation of priority queue ADTs
  • Uses and implementation of priority queues

4
Priority Queue Applications
  • External sorting
  • Discrete-event simulations
  • Very important for greedy algorithms (CHP9)
  • and optimization problems (CHP10)
  • Example ARAM system is greedy!!!

5
Motivation Problem
  • Queue the fancy name for waiting in line

6
Motivation Problem - At the Bank, bust stop
  • Queue at the counter or bus stop
  • Give priority to
  • Elderly
  • Pregnant
  • With baby

7
Motivation Problem Hospital
  • Patients waiting for help in Emergency Room
  • Give priority to
  • Severely wounded
  • Bleading
  • the ones with crash !!!

8
Motivation Problem - Operating System
  • Processes waiting for services
  • Printer
  • Multiuser environment
  • CPU
  • Give priority to
  • I/O bound
  • Interrups
  • Eg. small jobs(1page print) may be given priority
    over large jobs (100pages)

9
Review of Queues
10
Review Queue
  • FIFO
  • first come
  • first serve
  • One entry place
  • One exit place
  • No change in order
  • No priority
  • ARAM system is priority based!!!

public interface Queue extends Container
Object getHead() void enqueue(Object
object) Object dequeue()
  • G/G/m/K
  • General arrival process time
  • General service process time
  • m servers
  • K buffer size
  • Example M/M/1
  • Exponential arrival time
  • Exponential service time
  • Single server queue

11
Review Queue ADT
  • Sample operation

12
Review Queue Priorities - a few
  • If there is a need for change in the order
  • One queue for each priority
  • Algorithm
  • enqueue
  • put in to proper queue
  • dequeue
  • get from P1 first
  • then get from P2
  • then get from P3

P1
P2
P3
  • Application
  • MPEG layered approach
  • Base layer,
  • Enhancement layer

13
Review Queue Priorities - more
  • If there is a need for change in the order
  • One queue for each priority
  • Number of different priority categories is known
  • Algorithm
  • enqueue
  • put in to proper queue
  • dequeue
  • get from P1 first
  • then get from P2
  • then get from P3
  • then get from P123

P1
P2
P3
. . .
P123
14
Review Queue Priorities too many
  • If there is a need for change in the order
  • One queue for each priority
  • Number of different priority categories is unknown
  • Algorithm
  • enqueue
  • put in to proper queue
  • dequeue
  • get from P1 first
  • then get from P2
  • then get from P3
  • then get from P123

P1
P2
P3
. . .
P123
15
Priority Queues
16
Priority Queues Abstractions
  • Priority queue
  • A list of items
  • Each item has an associated priority
  • Insertion
  • Arbitrary order
  • Arbitrary priority
  • Deletion
  • Item with the lowest priority

17
Priority Queues Abstract Operations
  • enqueue
  • Puts an object in the container
  • findMin
  • Returns a reference to the smallest object
    (lowest priority) in the container
  • dequeueMin
  • Removes the smallest object from the container

18
Simple Implementationsfor priority queuea)
Simple link list b) Binary search
tree
19
Simple Implementations Using Simple Link Lists
  • Link is Unsorted Array
  • Insert at the front in O(1)
  • Delete after searching the min in O(n)
  • Link is Sorted Array
  • Insert in the order in O(n)
  • Delete at the end in O(1)
  • Not Use Unsorted Array, when there are more
    insertions than delete.

20
Simple Implementations Using Binary Search Tree
  • Average running time for Insert
  • O (log n)
  • Average running time for Deletion
  • O (log n)
  • Now, lets talk about the heaps in class hierarchy

21
Heap A heap is a binary tree storing keys
at its nodesIn order to understand the heap
structures lets review general tree structures
22
ReviewN-ary Tree
  • Definition
  • An N-ary tree T is a finite set of nodes  with
    the following properties
  • Either the set is empty, T ? or
  • The set consists of a root, R, and exactly N
    distinct N-ary trees. That is, the remaining
    nodes are partitioned into N?0 subsets,T0 , T1,
    , TN-1 , each of which is an N-ary tree such
    that T R , T0 , T1, , TN-1 .
  • Remark The empty tree, T ?, is a tree
  • Definition The empty trees are called external
    nodes  because they have no subtrees and
    therefore appear at the extremities of the tree.
    Conversely, the non-empty trees are called
    internal nodes.

23
Heap
  • Definition
  • A (Min) Heap   is a tree, T R , T0 , T1,
    , Tn-1 with the following properties
  • Every subtree of T is a heap and,
  • The root of T is less than or equal to the root
    of every subtree of T. That is, R ? Ri for all
    i, 0 ? i ? n , where Ri is the root of Ti .

  • Observations
  • Each node is less then all the subtrees of it.
  • No restrictions for the relative ordering of the
    subtrees.

24
Binary Heap
25
RecapPerfect Binary Tree
  • Definition
  • A perfect binary tree of height h?0 is a binary
    tree T R, TL, TR with the following
    properties
  • If h 0, TL ? and TR ?.
  • If h gt 0, thenTL is a perfect binary tree of
    height h-1. TR is a perfect binary tree of
    height h-1.

Theorem A perfect binary tree of height h has
exactly 2h1 - 1 internal nodes. TheoremThe
height of a perfect binary tree with n internal
nodes is log (n1).
26
Complete Binary Tree
  • Definition
  • A complete binary tree   of height h?0, is a
    binary tree TR, TL, TR with the following
    properties
  • If h0, TL ? and TR ?.
  • For hgt0 there are two possibilities
  • TL is a perfect binary tree of height h-1 and TR
    is a complete binary tree of height h-1
  • TL is a complete binary tree of height h-1 and
    TR is a perfect binary tree of height h-2.

27
Complete Binary Tree
  • 1
  • 1L
  • 2L
  • 2R is a complete binary tree of height 2
  • 5L is a perfect binary tree of height 1
  • 5R is a perfect binary tree of height 0
  • 1R

2R
5L
5R
28
Complete Binary Tree
  • 1
  • 1L is a complete binary tree of height 3 (2a)
  • 2L is a perfect binary tree of height 2
  • 2R is a complete binary tree of height 2
  • 5L is a perfect binary tree of height 1
  • 5R is a perfect binary tree of height 0
  • 1R

29
Complete Binary Tree
  • 1 is a complete binary tree of height 4 (2b)
  • 1L is a complete binary tree of height 3 (2a)
  • 2L is a perfect binary tree of height 2
  • 2R is a complete binary tree of height 2
  • 5L is a perfect binary tree of height 1
  • 5R is a perfect binary tree of height 0
  • 1R is a perfect binary tree of height 2

1L
1R
30
Complete Binary Tree Array representation
b 2a c 2a1 a ?b/2? a ?c/2?
31
Complete Binary Tree
  • Theorem
  • A complete binary tree of height h?0 contains
    at least 2h and at most 2h1 - 1 nodes.

32
Complete Binary Tree
  • Theorem
  • The internal path length of a binary tree with n
    nodes is at least as big as the internal path
    length of a complete binary tree with n nodes.
  • Definition
  • The internal path length of a tree is simply the
    sum of the depths (levels) of all the internal
    nodes in the tree

di is the depth of the ith node n is the number
of nodes
33
Complete N-ary Tree
  • Informally
  • a complete tree is a tree in which
  • all the levels are full except for the bottom
    level and
  • the bottom level is filled from left to right.

34
Complete N-ary Tree 
  • Definition
  • A complete N-ary tree   of height h?0, is an
    N-ary tree T R , T0 , T1, , TN-1 with the
    following properties
  • If h0, Ti ? for all i, 0 ? i lt N.
  • For hgt0 there exists a j, 0 ? j lt N such that a.
    Ti is a perfect binary tree of height h-1 for all
    i, 0 ? i lt j b. Tj is a complete binary tree of
    height h-1 c. Ti is a perfect binary tree of
    height h-2 for all i, jltiltN

35
Complete N-ary Tree  Array Representation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
20 21
Children of node i c1 N(i-1)2 c2 N(i-1)3 c3
N(i-1)4 cN Nii Parent of node i ?(i-1)N?

36
Heaps ()
  • A heap is a binary tree storing keys at its nodes
    and satisfying the following properties
  • Heap-Order for every internal node v other than
    the root,key(v) ? key(parent(v))
  • Complete Binary Tree let h be the height of the
    heap
  • for i 0, , h - 1, there are 2i nodes of depth
    i
  • at depth h - 1, the internal nodes are to the
    left of the external nodes
  • The last node of a heap is the rightmost node of
    depth h

2
6
5
7
9
last node
37
Height of a Heap ()
  • Theorem A heap storing n keys has height O(log
    n)
  • Proof (we apply the complete binary tree
    property)
  • Let h be the height of a heap storing n keys
  • Since there are 2i keys at depth i 0, , h - 1
    and at least one key at depth h, we have n ? 1
    2 4 2h-1 1
  • Thus, n ? 2h , i.e., h ? log n

keys
depth
1
0
2
1
2h-1
h-1
1
h
38
Heaps and Priority Queues
  • We can use a heap to implement a priority queue
  • We store a (key, element) item at each internal
    node
  • We keep track of the position of the last node
  • For simplicity, we show only the keys in the
    pictures

(2, Sue)
(6, Mark)
(5, Pat)
(9, Jeff)
(7, Anna)
39
Insertion into a Heap ()
  • Method insertItem of the priority queue ADT
    corresponds to the insertion of a key k to the
    heap
  • The insertion algorithm consists of three steps
  • Find the insertion node z (the new last node)
  • Store k at z
  • Restore the heap-order property (discussed next)

2
6
5
z
7
9
insertion node
2
6
5
z
7
9
1
40
Upheap (percolate up)
  • After the insertion of a new key k, the
    heap-order property may be violated!!!!
  • Algorithm upheap restores the heap-order property
    by swapping k along an upward path from the
    insertion node
  • Upheap terminates when the key k reaches the root
    or a node whose parent has a key smaller than or
    equal to k
  • Since a heap has height O(log n), upheap runs in
    O(log n) time

2
1
1
5
2
5
z
z
7
9
6
7
9
6
41
Removal from a Heap ()
  • Method removeMin of the priority queue ADT
    corresponds to the removal of the root key from
    the heap
  • The removal algorithm consists of three steps
  • Replace the root key with the key of the last
    node w
  • (since the last node was 7, now, 7 is the
    root key)
  • Remove w
  • Restore the heap-order property (discussed next)

2
6
5
w
7
9
last node
7
6
5
w
9
new last node
42
Downheap (percolate down)
  • After replacing the root key with the key k of
    the last node, the heap-order property may be
    violated!!!
  • Algorithm downheap restores the heap-order
    property by swapping key k along a downward path
    from the root
  • Upheap terminates when key k reaches a leaf or a
    node whose children have keys greater than or
    equal to k
  • Since a heap has height O(log n), downheap runs
    in O(log n) time

7
5
6
5
6
7
w
w
9
9
43
Updating the Last Node
  • The insertion node can be found by traversing a
    path of O(log n) nodes
  • Go up until a left child or the root is reached
  • If a left child is reached, go to the right child
  • Go down left until a leaf is reached
  • Similar algorithm for updating the last node
    after a removal

44
Heap-Sort () Other Sorting types
will be visited in CHP7
  • Consider a priority queue with n items
    implemented by means of a heap
  • the space used is O(n)
  • methods insert and removeMin take O(log n) time
  • methods size, isEmpty, and min take time O(1) time
  • Using a heap-based priority queue, we can sort a
    sequence of n elements in O(n log n) time
  • The resulting algorithm is called heap-sort
  • Heap-sort is much faster than quadratic sorting
    algorithms, such as insertion-sort and
    selection-sort

45
Vector-based Heap Implementation ()
  • We can represent a heap with n keys by means of a
    vector of length n 1
  • For the node at rank i
  • the left child is at rank 2i
  • the right child is at rank 2i 1
  • Links between nodes are not explicitly stored
  • The cell of at rank 0 is not used
  • Operation insert corresponds to inserting at rank
    n 1
  • Operation removeMin corresponds to removing at
    rank n
  • Yields in-place heap-sort

2
6
5
7
9
46
Merging Two Heaps
3
2
  • We are given two heaps and a key k
  • We create a new heap with the root node storing k
    and with the two heaps as subtrees
  • We perform downheap to restore the heap-order
    property

5
8
6
4
7
3
2
5
8
6
4
2
3
4
5
8
6
7
47
Bottom-up Heap Construction ()
  • We can construct a heap storing n given keys in
    using a bottom-up construction with log n phases
  • In phase i, pairs of heaps with 2i -1 keys are
    merged into heaps with 2i1-1 keys

2i1-1
48
Example
15
16
12
4
7
6
20
23
25
5
11
27
15
16
12
4
7
6
20
23
49
Example (contd.)
25
5
11
27
15
16
12
4
9
6
20
23
15
4
6
23
25
16
12
5
9
11
20
27
50
Example (contd.)
7
8
15
4
6
23
25
16
12
5
9
11
20
27
4
6
15
5
8
23
25
16
12
7
9
11
20
27
51
Example (end)
10
4
6
15
5
8
23
25
16
12
7
9
11
20
27
4
5
6
15
7
8
23
25
16
12
10
9
11
20
27
52
Analysis
  • We visualize the worst-case time of a downheap
    with a proxy path that goes first right and then
    repeatedly goes left until the bottom of the heap
    (this path may differ from the actual downheap
    path)
  • Since each node is traversed by at most two proxy
    paths, the total number of nodes of the proxy
    paths is O(n)
  • Thus, bottom-up heap construction runs in O(n)
    time
  • Bottom-up heap construction is faster than n
    successive insertions and speeds up the first
    phase of heap-sort

53
Priority Queues Priority Queue Interface
public interface PriorityQueue extends
Container void enqueue(Comparable
object) Comparable findMin() Comparable
dequeueMin()
  • enqueue
  • Puts an object in the priorityQueue
  • findMin
  • Returns a reference to the smallest object in the
    priorityQueue
  • dequeueMin
  • Removes the smallest object from the priorityQueue

54
Priority Queues Mergeable Priority Queue
Interface
public interface MergeablePriorityQueue extends
PriorityQueue void merge(MergeablePriorityQueu
e queue)
55
Priority Queues Mostly used Heap types
  • Binary Heap
  • d-heaps
  • Leftist Heap
  • Skew heaps
  • Binomial Heap

56
Binary Heap Implementation
57
Binary Heap Implementation Constructors
public class BinaryHeap / Construct the
binary heap. / public BinaryHeap()
this(DEFAULT_CAPACITY) / Construct
the binary heap. _at_param capacity the capacity
of the binary heap. / public BinaryHeap(int
capacity) currentSize 0 array new
Comparablecapacity 1
58
Binary Heap Implementation enqueue
59
Binary Heap Implementation enqueue
public class BinaryHeap / Insert into
the priority queue, maintaining heap order.
Duplicates are allowed. _at_param x the item to
insert. _at_exception Overflow if container is
full. / public void insert(Comparable x) throws
Overflow if (isFull()) throw new
Overflow() // Percolate up int hole
currentSize for ( hole gt 1
x.compareTo(arrayhole / 2) lt 0 hole /
2) arrayhole arrayhole / 2 arrayhole
x
60
Binary Heap Implementation enqueue
public class BinaryHeap / Insert into
the priority queue, maintaining heap order.
Duplicates are allowed. _at_param x the item to
insert. _at_exception Overflow if container is
full. / public void insert(Comparable x) throws
Overflow if (isFull()) throw new
Overflow() // Percolate up int hole
currentSize for ( hole gt 1
x.compareTo(arrayhole / 2) lt 0 hole /
2) arrayhole arrayhole / 2 arrayhole
x
  • weiss
  • Fig 6.6
  • Fig 6.7

Worst-case O(log n)
61
Binary Heap Implementation enqueue - Exacution
  • insert 14

62
Binary Heap Implementation enqueue - Exacution
  • insert 14

63
Binary Heap Implementation enqueue - Exacution
  • insert 14

64
Binary Heap Implementation enqueue - Exacution
  • insert 14

65
Binary Heap Implementation dequeue
66
Binary Heap Implementation dequeue
public class BinaryHeap / Remove the
smallest item from the priority queue. _at_return
the smallest item, or null, if empty. / public
Comparable deleteMin() if (isEmpty()) return
null Comparable minItem findMin() array1
arraycurrentSize-- percolateDown(1) retur
n minItem
67
Binary Heap Implementation dequeue
public class BinaryHeap / Remove the
smallest item from the priority queue. _at_return
the smallest item, or null, if empty. / public
Comparable deleteMin() if (isEmpty()) return
null Comparable minItem findMin() array1
arraycurrentSize-- percolateDown(1) retur
n minItem
public class BinaryHeap / Internal
method to percolate down in the heap. _at_param
hole the index at which the percolate begins.
/ private void percolateDown(int hole) int
child Comparable tmp arrayhole for (
hole 2 lt currentSize hole child) child
hole 2 // left if (child ! currentSize
arraychild 1.compareTo(arraychild) lt
0) child if (arraychild.compareTo(tmp)
lt 0) arrayhole arraychild else brea
k arrayhole tmp
68
Binary Heap Implementation dequeue
Worst-case O(log n)
public class BinaryHeap / Remove the
smallest item from the priority queue. _at_return
the smallest item, or null, if empty. / public
Comparable deleteMin() if (isEmpty()) return
null Comparable minItem findMin() array1
arraycurrentSize-- percolateDown(1) retur
n minItem
public class BinaryHeap / Internal
method to percolate down in the heap. _at_param
hole the index at which the percolate begins.
/ private void percolateDown(int hole) int
child Comparable tmp arrayhole for (
hole 2 lt currentSize hole child) child
hole 2 // left if (child ! currentSize
arraychild 1.compareTo(arraychild) lt
0) child if (arraychild.compareTo(tmp)
lt 0) arrayhole arraychild else brea
k arrayhole tmp
69
Binary Heap Implementation dequeue Execution
70
Binary Heap Implementation dequeue Execution
71
Binary Heap Implementation dequeue Execution
72
Binary Heap Implementation dequeue Execution
73
Binary Heap Implementation dequeue Execution
74
Binary Heap Implementation dequeue Execution
75
Binary Heap Implementation buildHeap
public class BinaryHeap / Establish
heap order property from an arbitrary
arrangement of items. Runs in linear time.
/ private void buildHeap() for (int i
currentSize / 2 i gt 0 i--) percolateDown(i)

public class BinaryHeap / Internal
method to percolate down in the heap. _at_param
hole the index at which the percolate begins.
/ private void percolateDown(int hole) int
child Comparable tmp arrayhole for (
hole 2 lt currentSize hole child) child
hole 2 // left if (child ! currentSize
arraychild 1.compareTo(arraychild) lt
0) child if (arraychild.compareTo(tmp)
lt 0) arrayhole arraychild else brea
k arrayhole tmp
76
Binary Heap Implementation buildHeap
public class BinaryHeap / Establish
heap order property from an arbitrary
arrangement of items. Runs in linear time.
/ private void buildHeap() for (int i
currentSize / 2 i gt 0 i--) percolateDown(i)

public class BinaryHeap / Internal
method to percolate down in the heap. _at_param
hole the index at which the percolate begins.
/ private void percolateDown(int hole) int
child Comparable tmp arrayhole for (
hole 2 lt currentSize hole child) child
hole 2 // left if (child ! currentSize
arraychild 1.compareTo(arraychild) lt
0) child if (arraychild.compareTo(tmp)
lt 0) arrayhole arraychild else brea
k arrayhole tmp
77
Binary Heap Implementation buildHeap
public class BinaryHeap / Internal
method to percolate down in the heap. _at_param
hole the index at which the percolate begins.
/ private void percolateDown(int hole) int
child Comparable tmp arrayhole for (
hole 2 lt currentSize hole child) child
hole 2 // left if (child ! currentSize
arraychild 1.compareTo(arraychild) lt
0) child if (arraychild.compareTo(tmp)
lt 0) arrayhole arraychild else brea
k arrayhole tmp
  • Weiss
  • Fig 6.15
  • 6.16
  • 6.17
  • 6.18

78
Binary Heap Implementation findMin
public class BinaryHeap / Find the
smallest item in the priority queue. _at_return
the smallest item, or null, if empty. / public
Comparable findMin() if (isEmpty()) return
null return array1
79
Binary Heap Implementation Best Practices
Header Sample
// BinaryHeap class // // CONSTRUCTION with
optional capacity (that defaults to 100) // //
PUBLIC OPERATIONS
// void insert( x ) --gt Insert x //
Comparable deleteMin( )--gt Return and remove
smallest item // Comparable findMin( ) --gt
Return smallest item // boolean isEmpty( )
--gt Return true if empty else false // boolean
isFull( ) --gt Return true if full else
false // void makeEmpty( ) --gt Remove all
items // ERRORS
// Throws Overflow if capacity
exceeded / Implements a binary heap.
Note that all "matching" is based on the
compareTo method. _at_author Mark Allen Weiss
/ public class BinaryHeap
80
Binary Heap Implementation Best Practices Test
Sample
  • Use main() for testing

public class BinaryHeap // Test
program public static void main(String args)
int numItems 10000 BinaryHeap h new
BinaryHeap(numItems) int i 37 try for
(i 37 i ! 0 i (i 37)
numItems) h.insert(new MyInteger(i)) for (i
1 i lt numItems i) if (((MyInteger)
(h.deleteMin())).intValue() ! i) System.out.p
rintln("Oops! " i) for (i 37 i ! 0 i
(i 37) numItems) h.insert(new
MyInteger(i)) h.insert(new MyInteger(0)) i
9999999 h.insert(new MyInteger(i)) for (i
1 i lt numItems i) if (((MyInteger)
(h.deleteMin())).intValue() ! i) System.out.p
rintln("Oops! " i " ") catch (Overflow e)
System.out.println("Overflow (expected)! "
i)
81
Binary Heap Implementation Complexity Summary
  • Binary

82
N-ary Heap Implementation Complexity Summary
  • N-ary

83
Leftist Trees
84
Leftist Tree
  • Mergeable priority queues
  • Leftist heaps

85
Leftist Trees Null Path
  • Definition
  • Consider an arbitrary node x in some binary tree
    T. The null path of node x is the shortest path
    in T from x to an external node of T.
  • The null path length  of node x is the length of
    its null path.
  • Definition
  • The null path length of an empty tree is zero.
  • The null path length of a non-empty binary tree
    TR, TL, TR is the null path length its root R.

86
Leftist Trees Leftist Tree
  • Definition
  • A leftist tree is a binary tree T with the
    following properties
  • Either T ? or
  • T R, TL, TR , where both TL and TR are leftist
    trees which have null path lengths dL and dL,
    respectively, such that dL ? dL
  • Remark A leftist tree is a tree in which the
    shortest path to an external node is always on
    the right.

87
Leftist Trees Length of the Right Path
  • Theorem
  • Consider a leftist tree T which contains n
    internal nodes. The path leading from the root of
    T downwards to the rightmost external node
    contains at most ?log2(n1)? nodes.

88
Leftist Trees Leftist Heaps
  • A heap-ordered tree
  • The positions of the keys in the tree
  • A leftist tree
  • The shape of the tree

89
Leftist Trees Merging Leftist Heaps
  • if h1 is empty, swap h1 and h2
  • otherwise, assume the root of h2 is larger than
    the root of h1
  • recursively merge h2 with the right subheap of h1
  • if the right subheap of h1 now has a larger null
    path length then its left subheap, swap the left
    and right subheaps
  • if h2 initially has the smaller root, exchange h1
    and h2 and proceed as above

90
Leftist Trees Implementation - LeftHeapNode
// Basic node stored in leftist heaps // Note
that this class is not accessible outside // of
package DataStructures class LeftHeapNode
// Constructors LeftHeapNode(Comparable
theElement) this(theElement, null,
null) LeftHeapNode(Comparable
theElement, LeftHeapNode lt, LeftHeapNode rt)
element theElement left lt
right rt npl 0 //
Friendly data accessible by other package
routines Comparable element // The data in
the node LeftHeapNode left // Left child
LeftHeapNode right // Right child int npl
// null path length
91
Leftist Trees Implementation Merging
public class LeftistHeap /
Merge rhs into the priority queue. rhs
becomes empty. rhs must be different from this.
_at_param rhs the other leftist heap. /
public void merge(LeftistHeap rhs) if
(this rhs) // Avoid aliasing problems
return root merge(root,
rhs.root) rhs.root null
/ Internal static method to merge two
roots. Deals with deviant cases and calls
recursive merge1. / private static
LeftHeapNode merge(LeftHeapNode h1,
LeftHeapNode h2)
if (h1 null) return h2
if (h2 null) return h1 if
(h1.element.compareTo(h2.element) lt 0)
return merge1(h1, h2) else
return merge1(h2, h1)
92
Leftist Trees Implementation Merging
public class LeftistHeap /
Merge rhs into the priority queue. rhs
becomes empty. rhs must be different from this.
_at_param rhs the other leftist heap. /
public void merge(LeftistHeap rhs) if
(this rhs) // Avoid aliasing problems
return root merge(root,
rhs.root) rhs.root null
/ Internal static method to merge two
roots. Deals with deviant cases and calls
recursive merge1. / private static
LeftHeapNode merge(LeftHeapNode h1,
LeftHeapNode h2)
if (h1 null) return h2
if (h2 null) return h1 if
(h1.element.compareTo(h2.element) lt 0)
return merge1(h1, h2) else
return merge1(h2, h1)
/ Internal static method to
merge two roots. Assumes trees are not
empty, and h1's root contains smallest
item. / private static LeftHeapNode
merge1(LeftHeapNode h1,
LeftHeapNode h2) if
(h1.left null) // Single node
h1.left h2 // Other fields in h1 already
accurate else h1.right
merge(h1.right, h2) if (h1.left.npl
lt h1.right.npl)
swapChildren(h1) h1.npl
h1.right.npl 1 return h1
/ Swaps t's two children.
/ private static void swapChildren(LeftHeapNo
de t) LeftHeapNode tmp t.left
t.left t.right t.right tmp

93
Leftist Trees Implementation enqueue()
public class LeftistHeap /
Insert into the priority queue,
maintaining heap order. _at_param x the item
to insert. / public void
insert(Comparable x) root merge(new
LeftHeapNode(x), root)
94
Leftist Trees Implementation findMin()
public class LeftistHeap /
Find the smallest item in the priority queue.
_at_return the smallest item, or null, if empty.
/ public Comparable findMin()
if (isEmpty()) return null
return root.element
95
Leftist Trees Implementation dequeueMin()
public class LeftistHeap /
Remove the smallest item from the priority
queue. _at_return the smallest item, or null,
if empty. / public Comparable
deleteMin() if (isEmpty())
return null Comparable minItem
root.element root merge(root.left,
root.right) return minItem

96
Leftist Trees Complexity Summary
97
Binomial Queues
98
Binomial Queues
  • binomial queues
  • binomial trees
  • forests
  • merging of binomial queues

99
Binomial Queues
  • Definition
  • The binomial tree of order k ? 0 with root R is
    the tree Bk defined as follows
  • If k 0, B0 R. i.e., the binomial tree of
    order zero consists of a single node, R.
  • If k gt 0, Bk R, B0, B1, , Bk-1. i.e., the
    binomial tree of order k gt 0 comprises the root
    R, and k binomial subtrees, B0, B1, . . . , Bk-1.

100
Binomial Queues Different Views
101
Binomial Queues Number of Nodes
  • Theorem
  • The binomial tree of order k, Bk, contains 2k
    nodes.

102
Binomial Queues Height
  • Theorem
  • The height of the binomial tree of order k, Bk,
    is k.

103
Binomial Queues Binomial Theorem
  • Theorem
  • The nth power of the binomial xy for n ? 0 is
    given bywhere is called
    binomial coefficient

104
Binomial Queues Why Binomial ?
  • Theorem
  • The number of nodes at level l in Bk, the
    binomial tree of order k, where 0 l k, is
    given by the binomial coefficient
  • level
  • 0 1 2 3 4 ...
  • 1
  • 1 1
  • 1 2 1
  • 1 3 3 1
  • 4 6 4 1
  • ...

k 0 1 2 3 4 ...
105
Binomial Queues Any Size ?
  • Binomial trees only come in sizes that are a
    power of 2
  • How to represent arbitrary number, n, of items?
  • Consider the binary representation of the number
    n
  • where bi ? 0, 1 is
    the ith bit
  • To hold n items use a forest of binomial
    treesFn Bi bi 1

106
Binomial Queues Merging Binomial Queues
  • Merging two binomial queues is like doing binary
    addition

107
Binomial Queues Merging Binomial Queues ...
108
HW in CHP6 4, 6, 14, 15, 22,26,27
  • 6.1 Yes. When an element is inserted, we compare
    it to the current minimum and change the minimum
    if the new element is smaller. deleteMin
    operations are expensive in this scheme.
  • 6.2
  • 1
  • 3
    2
  • 6 7 5
    4
  • 15 14 12 9 10 11
    13 8
  • 1
  • 3
    2
  • 12 6 4
    8
  • 15 14 9 7 5 11
    13 10

109
References
  • Data Structures and Algorithms with
    Object-Oriented Design Patterns in JavaPreiss
    http//www.brpreiss.com/books/opus5/
  • Data Structures and Algorithmswith
    Object-Oriented Design Patters in
    CPreissWiley, 1999
  • Data Structures and Algorithm Analysis in
    JavaWeissAddison-Wesley, 1999

110
Debuging Tools()
111
Debuging Tools
______binary tree______ . / -4 \
. ______binary tree______ . / -4
\ . / -2 \ . ______binary tree______
. / -4 \ . / -2 \ . /
-6 \ . ______binary tree______
. / -7 \ . / -4
\ . / -2 \ . / -6 \
. ______binary tree______ . /
-7 \ . / -2 \
. / -4 \ . / -1 \
. / -6 \ .
public static void main(String args)
int numItems 10000 BinaryHeap h
new BinaryHeap(numItems) switch (1)
case 1 try
h.insert(new MyInteger(4))
h.printTree()
h.insert(new MyInteger(2))
h.printTree() h.insert(new
MyInteger(6))
h.printTree() h.insert(new
MyInteger(7))
h.printTree() h.insert(new
MyInteger(1))
h.printTree() catch (Overflow
e1) // TODO Auto-generated
catch block
e1.printStackTrace()
break case 2
... break default
break
112
Debuging Tools
public void printTree()
System.out.println("______binary tree______")
if (isEmpty())
System.out.println("Empty tree") else
printTree(1, 0) public void
printTree(String name)
System.out.println("______" name "______")
if (isEmpty())
System.out.println("Empty tree") else
printTree(1, 0) private void
printTree(int t, int depth) String
space "" for (int i 0 i lt depth
i) space " "
if (t lt currentSize) int d
depth printTree(2 t, d)
System.out.println(space "/")
System.out.print(space "-")
System.out.println(arrayt)
System.out.println(space "\\")
printTree(2 t 1, d) else
System.out.println(space ".")

113
Debuging Tools
public void printTree()
System.out.println("______binary tree______")
if (isEmpty())
System.out.println("Empty tree") else
printTree(1, 0) public void
printTree(String name)
System.out.println("______" name "______")
if (isEmpty())
System.out.println("Empty tree") else
printTree(1, 0) private void
printTree(int t, int depth) String
space "" for (int i 0 i lt depth
i) space " "
if (t lt currentSize) int d
depth printTree(2 t, d)
System.out.println(space "/")
System.out.print(space "-")
System.out.println(arrayt)
System.out.println(space "\\")
printTree(2 t 1, d) else
System.out.println(space ".")

... int numItems 10000 BinaryHeap h new
BinaryHeap(numItems) h.insert(new
MyInteger(4)) h.insert(new MyInteger(2)) h.inser
t(new MyInteger(6)) h.insert(new
MyInteger(7)) h.insert(new MyInteger(1)) h.print
Tree() ...
______binary tree______ . /
-7 \ . / -2 \ .
/ -4 \ . / -1 \
. / -6 \ .
114
Class Hierarchy Priority Queues- Heap ()
  • Container

PriorityQueue
Tree
BinaryHeap
MergeablePriorityQueue
BinaryTree
GeneralTree
BinomialQueue
LeftistHeap
BinomialTree
Write a Comment
User Comments (0)
About PowerShow.com