1 c++ plus data structures nell dale chapter 7 programming with recursion modified from the slides...

66
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus

Upload: cameron-rogers

Post on 26-Dec-2015

231 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

1

C++ Plus Data Structures

Nell Dale

Chapter 7

Programming with Recursion

Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus

Page 2: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

2

Recursive Function Call

A recursive call is a function call in which the called function is the same as the one making the call.

In other words, recursion occurs when a function calls itself!

We must avoid making an infinite sequence of function calls (infinite recursion).

Page 3: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

3

Finding a Recursive Solution

Each successive recursive call should bring you closer to a situation in which the answer is known.

A case for which the answer is known (and can be expressed without recursion) is called a base case.

Each recursive algorithm must have at least one base case, as well as the general (recursive) case

Page 4: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

4

Three-Question Method of verifying recursive functions

Base-Case Question: Is there a nonrecursive way out of the function?

Smaller-Caller Question: Does each recursive function call involve a smaller case of the original problem leading to the base case?

General-Case Question: Assuming each recursive call works correctly, does the whole function work correctly?

Page 5: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

5

Writing Recursive Functions

Get an exact definition of the problem to be solved.

Determine the size of the problem on this call to the function.

Identify and solve the base case(s).

Identify and solve the general case(s) in terms of a smaller case of the same problem – a recursive call.

Page 6: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

6

“Why use recursion?”

Those examples could have been written without recursion, using iteration instead. The iterative solution uses a loop, and the recursive solution uses an if statement.

However, for certain problems the recursive solution is the most natural solution. This often occurs when pointer variables are used.

Page 7: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

7

Recursive Linked List Processing

Page 8: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

8

struct NodeType{

int info ;NodeType* next ;

}

class SortedType {public :

. . . // member function prototypes

private :

NodeType* listData ;

} ;

struct ListType

Page 9: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

9

RevPrint(listData);

A B C D E

FIRST, print out this section of list, backwards

THEN, print this element

listData

Page 10: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

10

Base Case and General Case

A base case may be a solution in terms of a “smaller” list. Certainly for a list with 0 elements, there is no more processing to do.

Our general case needs to bring us closer to the base case situation. That is, the number of list elements to be processed decreases by 1 with each recursive call. By printing one element in the general case, and also processing the smaller remaining list, we will eventually reach the situation where 0 list elements are left to be processed.

In the general case, we will print the elements of the smaller remaining list in reverse order, and then print the current pointed to element.

Page 11: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

11

Using recursion with a linked list

void RevPrint ( NodeType* listPtr )

// Pre: listPtr points to an element of a list.

// Post: all elements of list pointed to by listPtr have been printed

// out in reverse order.

{

if ( listPtr != NULL ) // general case

{

RevPrint ( listPtr-> next ) ; // process the rest

cout << listPtr->info << endl ; // then print this element

}

// Base case : if the list is empty, do nothing

}11

Page 12: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

12

How Recursion Works

Static storage allocation associates variable names with memory locations at compile time.

Dynamic storage allocation associates variable names with memory locations at execution time.

Page 13: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

13

When a function is called...

A transfer of control occurs from the calling block to the code of the function. It is necessary that there is a return to the correct place in the calling block after the function code is executed. This correct place is called the return address.

When any function is called, the run-time stack is used. On this stack is placed an activation record (stack frame) for the function call.

Page 14: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

14

Stack Activation Frames The activation record stores the return address

for this function call, and also the parameters, local variables, and the function’s return value, if non-void.

The activation record for a particular function call is popped off the run-time stack when the final closing brace in the function code is reached, or when a return statement is reached in the function code.

At this time the function’s return value, if non-void, is brought back to the calling block return address for use there.

Page 15: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

15

Debugging Recursive Routines

Using the Three-Question Method.

Using a branching statement (if/switch).

Put debug output statement during testing.

Page 16: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

16

Removing Recursion

When the language doesn’t support recursion, or recursive solution is too costly (space or time), or …

Iteration

Stacking

Page 17: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

17

Use a recursive solution when:

The depth of recursive calls is relatively “shallow” compared to the size of the problem.

The recursive version does about the same amount of work as the nonrecursive version.

The recursive version is shorter and simpler than the nonrecursive solution.

SHALLOW DEPTH EFFICIENCY CLARITY

Page 18: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

18

Nell Dale

Chapter 8

Binary Search Trees

Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus

C++ Plus Data Structures

Page 19: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

19

for an element in a sorted list stored sequentially

in an array: O(Log2N) in a linked list: ? (midpoint = ?)

Binary search

Page 20: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

20

Introduce some basic tree vocabulary

Develop algorithms

Implement operations needed to use a binary search tree

Goals of this chapter

Page 21: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

21

A binary tree is a structure in which:

Each node can have at most two children, and in which a unique path exists from the root to every other node.

The two children of a node are called the left child and the right child, if they exist.

Binary Tree

Page 22: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

22

Implementing a Binary Tree with Pointers and Dynamic Data

Q

V

T

K S

A E

L

Page 23: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

23

Each node contains two pointers

template< class ItemType >struct TreeNode {

ItemType info; // Data member

TreeNode<ItemType>* left; // Pointer to left child

TreeNode<ItemType>* right; // Pointer to right child

};

. left . info . right

NULL ‘A’ 6000

Page 24: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

// BINARY SEARCH TREE SPECIFICATION

template< class ItemType >

class TreeType { public:

TreeType ( ); // constructor ~TreeType ( ); // destructor bool IsEmpty ( ) const; bool IsFull ( ) const; int NumberOfNodes ( ) const; void InsertItem ( ItemType item ); void DeleteItem (ItemType item ); void RetrieveItem ( ItemType& item, bool& found ); void PrintTree (ofstream& outFile) const;

. . .

private:

TreeNode<ItemType>* root;}; 24

Page 25: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

25

TreeType<char> CharBST;

‘J’

‘E’

‘A’

‘S’

‘H’

TreeType

~TreeType

IsEmpty

InsertItem

Private data:

root

RetrieveItem

PrintTree . . .

Page 26: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

26

A Binary Tree

Q

V

T

K S

A E

L

Search for ‘S’?

Page 27: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

27

A special kind of binary tree in which:

1. Each node contains a distinct data value,

2. The key values in the tree can be compared using “greater than” and “less than”, and

3. The key value of each node in the tree is

less than every key value in its right subtree, and greater than every key value in its left subtree.

A Binary Search Tree (BST) is . . .

Page 28: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

28

Is ‘F’ in the binary search tree?

‘J’

‘E’

‘A’ ‘H’

‘T’

‘M’

‘K’

‘V’

‘P’ ‘Z’‘D’

‘Q’‘L’‘B’

‘S’

Page 29: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

29

Is ‘F’ in the binary search tree?

‘J’

‘E’

‘A’ ‘H’

‘T’

‘M’

‘K’

‘V’

‘P’ ‘Z’‘D’

‘Q’‘L’‘B’

‘S’

Page 30: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

// BINARY SEARCH TREE SPECIFICATION

template< class ItemType >

class TreeType { public:

TreeType ( ) ; // constructor ~TreeType ( ) ; // destructor bool IsEmpty ( ) const ; bool IsFull ( ) const ; int NumberOfNodes ( ) const ; void InsertItem ( ItemType item ) ; void DeleteItem (ItemType item ) ; void RetrieveItem ( ItemType& item , bool& found ) ; void PrintTree (ofstream& outFile) const ;

. . .

private:

TreeNode<ItemType>* root ;}; 30

Page 31: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

// SPECIFICATION (continued) // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -// RECURSIVE PARTNERS OF MEMBER FUNCTIONS

template< class ItemType >void PrintHelper ( TreeNode<ItemType>* ptr,

ofstream& outFile ) ;

template< class ItemType > void InsertHelper ( TreeNode<ItemType>*& ptr,

ItemType item ) ;

template< class ItemType > void RetrieveHelper ( TreeNode<ItemType>* ptr,

ItemType& item, bool& found ) ;

template< class ItemType > void DestroyHelper ( TreeNode<ItemType>* ptr ) ;

31

Page 32: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

template< class ItemType > void TreeType<ItemType> :: RetrieveItem ( ItemType& item,

bool& found ){ RetrieveHelper ( root, item, found ) ; }

template< class ItemType > void RetrieveHelper ( TreeNode<ItemType>* ptr, ItemType& item,

bool& found){ if ( ptr == NULL )

found = false ; else if ( item < ptr->info ) // GO LEFT

RetrieveHelper( ptr->left , item, found ) ; else if ( item > ptr->info ) // GO RIGHT

RetrieveHelper( ptr->right , item, found ) ; else { item = ptr->info ;

found = true ; }}

32

Page 33: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

template< class ItemType > void TreeType<ItemType> :: InsertItem ( ItemType item ){

InsertHelper ( root, item ) ; }

template< class ItemType > void InsertHelper ( TreeNode<ItemType>*& ptr, ItemType item ){ if ( ptr == NULL ) { // INSERT item HERE AS LEAF

ptr = new TreeNode<ItemType> ;ptr->right = NULL ;ptr->left = NULL ;ptr->info = item ;

} else if ( item < ptr->info ) // GO LEFT

InsertHelper( ptr->left , item ) ; else if ( item > ptr->info ) // GO RIGHT

InsertHelper( ptr->right , item ) ;} 33

Page 34: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

34

Traverse a list:

-- forward

-- backward

Traverse a tree:

-- there are many ways!

PrintTree()

Page 35: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

35

Inorder Traversal: A E H J M T Y

‘J’

‘E’

‘A’ ‘H’

‘T’

‘M’ ‘Y’

tree

Print left subtree first Print right subtree last

Print second

Page 36: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

36

Preorder Traversal: J E A H T M Y

‘J’

‘E’

‘A’ ‘H’

‘T’

‘M’ ‘Y’

tree

Print left subtree second Print right subtree last

Print first

Page 37: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

37

‘J’

‘E’

‘A’ ‘H’

‘T’

‘M’ ‘Y’

tree

Print left subtree first Print right subtree second

Print last

Postorder Traversal: A H E M Y T J

Page 38: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

38

Is the depth of recursion relatively shallow?

Yes. Is the recursive solution shorter or clearer than the

nonrecursive version?

Yes. Is the recursive version much less efficient than the

nonrecursive version?

No.

Recursion or Iteration?Assume: the tree is well balanced.

Page 39: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

39

Use a recursive solution when (Chpt. 7):

The depth of recursive calls is relatively “shallow” compared to the size of the problem.

The recursive version does about the same amount of work as the nonrecursive version.

The recursive version is shorter and simpler than the nonrecursive solution.

SHALLOW DEPTH EFFICIENCY CLARITY

Page 40: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

40

BST:

Quick random-access with the flexibility of a linked structure

Can be implemented elegantly and concisely using recursion

Takes up more memory space than a singly linked list

Algorithms are more complicated

Binary Search Trees (BSTs) vs. Linear Lists

Page 41: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

41

Nell Dale

Chapter 9

Trees Plus

Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus

C++ Plus Data Structures

Page 42: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

42

A special kind of binary tree in which:

1. Each leaf node contains a single operand,

2. Each nonleaf node contains a single binary operator, and

3. The left and right subtrees of an operator node represent subexpressions that must be evaluated before applying the operator at the root of the subtree.

A Binary Expression Tree is . . .

Page 43: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

43

Levels Indicate Precedence

When a binary expression tree is used to represent an expression, the levels of the nodes in the tree indicate their relative precedence of evaluation.

Operations at higher levels of the tree are evaluated later than those below them. The operation at the root is always the last operation performed.

Page 44: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

44

A Binary Expression Tree

‘*’

‘+’

‘4’

‘3’

‘2’

Infix: ( ( 4 + 2 ) * 3 )

Prefix: * + 4 2 3

Postfix: 4 2 + 3 * has operators in order used

Page 45: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

45

Inorder Traversal: (A + H) / (M - Y)

‘/’

‘+’

‘A’ ‘H’

‘-’

‘M’ ‘Y’

tree

Print left subtree first Print right subtree last

Print second

Page 46: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

46

Preorder Traversal: / + A H - M Y

‘/’

‘+’

‘A’ ‘H’

‘-’

‘M’ ‘Y’

tree

Print left subtree second Print right subtree last

Print first

Page 47: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

47

‘/’

‘+’

‘A’ ‘H’

‘-’

‘M’ ‘Y’

tree

Print left subtree first Print right subtree second

Print last

Postorder Traversal: A H + M Y - /

Page 48: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

48

Function Eval()

• Definition: Evaluates the expression represented by the binary tree.

• Size: The number of nodes in the tree.

• Base Case: If the content of the node is an operand, Func_value = the value of the operand.

• General Case: If the content of the node is an operator BinOperator,

Func_value = Eval(left subtree) BinOperator

Eval(right subtree)

Page 49: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

49

Writing Recursive Functions (Chpt 7)

Get an exact definition of the problem to be solved.

Determine the size of the problem on this call to the function.

Identify and solve the base case(s).

Identify and solve the general case(s) in terms of a smaller case of the same problem – a recursive call.

Page 50: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

50

Eval(TreeNode * tree)

Algorithm:

IF Info(tree) is an operandReturn Info(tree)

ELSE SWITCH(Info(tree)) case + :Return Eval(Left(tree)) + Eval(Right(tree)) case - : Return Eval(Left(tree)) - Eval(Right(tree)) case * : Return Eval(Left(tree)) * Eval(Right(tree)) case / : Return Eval(Left(tree)) / Eval(Right(tree))

Page 51: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

int Eval ( TreeNode* ptr )

// Pre: ptr is a pointer to a binary expression tree.// Post: Function value = the value of the expression represented// by the binary tree pointed to by ptr.

{ switch ( ptr->info.whichType ) {

case OPERAND : return ptr->info.operand ;case OPERATOR : switch ( tree->info.operation ) { case ‘+’ : return ( Eval ( ptr->left ) + Eval ( ptr->right ) ) ;

case ‘-’ : return ( Eval ( ptr->left ) - Eval ( ptr->right ) ) ;

case ‘*’ : return ( Eval ( ptr->left ) * Eval ( ptr->right ) ) ;

case ‘/’ : return ( Eval ( ptr->left ) / Eval ( ptr->right ) ) ; } }}

51

Page 52: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

52

A Nonlinked Representation ofBinary Trees

Store a binary tree in an array in such a way that the parent-child relationships are not lost

Page 53: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

53

A full binary tree

A full binary tree is a binary tree in which all the leaves are on the same level and every non leaf node has two children.

SHAPE OF A FULL BINARY TREE

Page 54: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

54

A complete binary tree

A complete binary tree is a binary tree that is either full or full through the next-to-last level, with the leaves on the last level as far to the left as possible.

SHAPE OF A COMPLETE BINARY TREE

Page 55: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

55

What is a Heap?

A heap is a binary tree that satisfies these

special SHAPE and ORDER properties:

Its shape must be a complete binary tree.

For each node in the heap, the value stored in that node is greater than or equal to the value in each of its children.

Page 56: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

56

70

0

60

1

40

3

30

4

12

2

8

5

tree

And use the numbers as array indexes to store the tree

[ 0 ]

[ 1 ]

[ 2 ]

[ 3 ]

[ 4 ]

[ 5 ]

[ 6 ]

70

60

12

40

30

8

tree.nodes

Page 57: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

57

Parent-Child Relationship?

tree.nodes[index]:left child: tree.nodes[index*2 + 1]right child: tree.nodes[index*2 + 2]parent: tree.nodes[(index-1) / 2]

Leaf nodes: tree.nodes[numElements / 2]…tree.nodes[numElements - 1]

Page 58: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

// HEAP SPECIFICATION

// Assumes ItemType is either a built-in simple data type// or a class with overloaded realtional operators.

template< class ItemType >struct HeapType

{ void ReheapDown ( int root , int bottom ) ;

void ReheapUp ( int root, int bottom ) ;

ItemType* elements ; // ARRAY to be allocated dynamically

int numElements ;

};

58

Page 59: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

59

ReheapDown(root, bottom)

IF elements[root] is not a leaf

Set maxChild to index of child with larger value

IF elements[root] < elements[maxChild])

Swap(elements[root], elements[maxChild]) ReheapDown(maxChild, bottom)

Page 60: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

60

// IMPLEMENTATION OF RECURSIVE HEAP MEMBER FUNCTIONS

template< class ItemType >void HeapType<ItemType>::ReheapDown ( int root, int bottom )

// Pre: root is the index of the node that may violate the heap // order property// Post: Heap order property is restored between root and bottom

{ int maxChild ; int rightChild ; int leftChild ;

leftChild = root * 2 + 1 ; rightChild = root * 2 + 2 ; 60

ReheapDown()

Page 61: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

if ( leftChild <= bottom ) // ReheapDown continued {

if ( leftChild == bottom ) maxChild = leftChld ;else{ if (elements [ leftChild ] <= elements [ rightChild ] )

maxChild = rightChild ; else

maxChild = leftChild ;}if ( elements [ root ] < elements [ maxChild ] ){ Swap ( elements [ root ] , elements [ maxChild ] ) ; ReheapDown ( maxChild, bottom ) ;}

}}

61

Page 62: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

62

Priority Queue

A priority queue is an ADT with the property that only the highest-priority element can be accessed at any time.

Page 63: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

Priority Queue ADT Specification

Structure: The Priority Queue is arranged to support

access to the highest priority item

Operations: MakeEmpty Boolean IsEmpty Boolean IsFull Enqueue(ItemType newItem) Dequeue(ItemType& item)

63

Page 64: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

Implementation Level

Algorithm:

Dequeue(): O(log2N) Set item to root element from queue Move last leaf element into root position Decrement numItems items.ReheapDown(0, numItems-1)

Enqueue(): O(log2N) Increment numItems Put newItem in next available position items.ReheapUp(0, numItems-1)

64

Page 65: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

Comparison of Priority Queue Implementations

65

Enqueue Dequeue

Heap O(log2N) O(log2N)

Linked List O(N) O(1)

Binary Search Tree

Balanced O(log2N) O(log2N)

Skewed O(N) O(N)

Trade-offs: read Text page 548

Page 66: 1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County

66

End