9 Priority Queues, Heaps, and Graphs. 9-2 What is a Heap? A heap is a binary tree that satisfies these special SHAPE and ORDER properties: –Its shape.

Slides:



Advertisements
Similar presentations
CMSC 341 Binary Heaps Priority Queues. 8/3/2007 UMBC CSMC 341 PQueue 2 Priority Queues Priority: some property of an object that allows it to be prioritized.
Advertisements

1 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.
Graphs Graphs are the most general data structures we will study in this course. A graph is a more general version of connected nodes than the tree. Both.
Graphs CS3240, L. grewe.
1 Nell Dale Chapter 9 Trees Plus Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
1 A Two-Level Binary Expression ‘-’ ‘8’ ‘5’ treePtr INORDER TRAVERSAL : has value 3 PREORDER TRAVERSAL: POSTORDER TRAVERSAL: 8 5 -
1 Heaps & Priority Queues (Walls & Mirrors - Remainder of Chapter 11)
CS 315 March 24 Goals: Heap (Chapter 6) priority queue definition of a heap Algorithms for Insert DeleteMin percolate-down Build-heap.
heaps1 Trees IV: The Heap heaps2 Heap Like a binary search tree, a heap is a binary tree in which the data entries can be compared using total order.
1 C++ Plus Data Structures Nell Dale Chapter 10 Sorting and Searching Algorithms Slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
Priority Queues, Heaps CS3240, L. grewe 1. 2 Goals Describe a priority queue at the logical level and implement a priority queue as a list Describe the.
Heaps CS 308 – Data Structures.
Lists A list is a finite, ordered sequence of data items. Two Implementations –Arrays –Linked Lists.
1 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Binary Trees A binary tree is made up of a finite set of nodes that is either empty or consists of a node called the root together with two binary trees,
Chapter 9 Heaps and Priority Queues. 9-2 What is a Heap? A heap is a binary tree that satisfies these special SHAPE and ORDER properties: –Its shape must.
CS 206 Introduction to Computer Science II 11 / 03 / 2008 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 11 / 05 / 2008 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 03 / 25 / 2009 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 11 / 09 / 2009 Instructor: Michael Eckmann.
Implementing a Queue as a Linked Structure CS 308 – Data Structures.
Important Problem Types and Fundamental Data Structures
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 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Heaps and Priority Queues CS 3358 – Data Structures.
Compiled by: Dr. Mohammad Alhawarat BST, Priority Queue, Heaps - Heapsort CHAPTER 07.
Computer Science and Software Engineering University of Wisconsin - Platteville 12. Heap Yan Shi CS/SE 2630 Lecture Notes Partially adopted from C++ Plus.
1 Chapter 9 Graph Algorithms Real-life graph problems Algorithms for some graph problems Choice of data structures for graph problems.
1 Joe Meehean. A A B B D D I I C C E E X X A A B B D D I I C C E E X X  Terminology each circle is a node pointers are edges topmost node is the root.
Chapter 9 Priority Queues, Heaps, Graphs, and Sets.
Chapter 9 Priority Queues, Heaps, and Graphs. 2 Goals Describe a priority queue at the logical level and implement a priority queue as a list Describe.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Graphs.
data ordered along paths from root to leaf
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Graphs.
CMSC 341 Binary Heaps Priority Queues. 2 Priority: some property of an object that allows it to be prioritized WRT other objects (of the same type) Priority.
Chapter 9 Priority Queues, Heaps, Graphs 1 Fall 2010.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 8 Prepared by İnanç TAHRALI.
Priority Queues (Heaps)
1 Chapter 13-1 Applied Arrays: Lists and Strings Dale/Weems.
Chapter 16 – Data Structures and Recursion. Data Structures u Built-in –Array –struct u User developed –linked list –stack –queue –tree Lesson 16.1.
CPSC 252 Binary Heaps Page 1 Binary Heaps A complete binary tree is a binary tree that satisfies the following properties: - every level, except possibly.
– Graphs 1 Graph Categories Strong Components Example of Digraph
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
FALL 2005CENG 213 Data Structures1 Priority Queues (Heaps) Reference: Chapter 7.
1 Joe Meehean. A A B B D D I I C C E E X X A A B B D D I I C C E E X X  Terminology each circle is a node pointers are edges topmost node is the root.
CSI 312 Dr. Yousef Qawqzeh Heaps and Priority Queue.
Sorting and Searching Algorithms CS Sorting means... l The values stored in an array have keys of a type for which the relational operators are.
Properties: -The value in each node is greater than all values in the node’s subtrees -Complete tree! (fills up from left to right) Max Heap.
2 Binary Heaps What if we’re mostly concerned with finding the most relevant data?  A binary heap is a binary tree (2 or fewer subtrees for each node)
Graphs and Shortest Paths Using ADTs and generic programming.
Heaps CS 302 – Data Structures Sections 8.8, 9.1, and 9.2.
Chapter 9 Heaps and Priority Queues Lecture 18. Full Binary Tree Every non-leaf node has two children Leaves are on the same level Full Binary Tree.
Course: Programming II - Abstract Data Types HeapsSlide Number 1 The ADT Heap So far we have seen the following sorting types : 1) Linked List sort by.
Lecture 22 Chapter 9 Sets.
Chapter 9 Priority Queues, Heaps, Graphs, and Sets
Sorting means The values stored in an array have keys of a type for which the relational operators are defined. (We also assume unique keys.) Sorting.
Tree Representation Heap.
Heaps A heap is a binary tree.
CS Data Structures Chapter 17 Heaps Mehmet H Gunes
C++ Plus Data Structures
Chapter 9 Priority Queues and Sets
Heaps and Priority Queues
Chapter 10 Sorting Algorithms
Important Problem Types and Fundamental Data Structures
C++ Plus Data Structures
Chapter 9 The Priority Queue ADT
Heaps Chapter 6 Section 6.9.
Presentation transcript:

9 Priority Queues, Heaps, and Graphs

9-2 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.

9-3 Are these Both Heaps? C A T treePtr

9-4 Is this a Heap? tree

9-5 Where is the Largest Element in a Heap Always Found? tree

9-6 We Can Number the Nodes Left to Right by Level This Way tree

9-7 And use the Numbers as Array Indexes to Store the Trees tree [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes

9-8 // HEAP SPECIFICATION // Assumes ItemType is either a built-in simple data // type or a class with overloaded relational operators. template struct HeapType { void ReheapDown ( int root, int bottom ) ; void ReheapUp ( int root, int bottom ) ; ItemType* elements; //ARRAY to be allocated dynamically int numElements ; };

9-9 ReheapDown // IMPLEMENTATION OF RECURSIVE HEAP MEMBER FUNCTIONS template void HeapType ::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 * ; rightChild = root * ;

9-10 ReheapDown (cont) 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 ) ; }

9-11 At the End of the Second Iteration of the Loop

9-12 // IMPLEMENTATIONcontinued template void HeapType ::ReheapUp ( int root, int bottom ) // Pre: bottom is the index of the node that may violate the heap // order property. The order property is satisfied from root to // next-to-last node. // Post: Heap order property is restored between root and bottom { int parent ; if ( bottom > root ) { parent = ( bottom - 1 ) / 2; if ( elements [ parent ] < elements [ bottom ] ) { Swap ( elements [ parent ], elements [ bottom ] ) ; ReheapUp ( root, parent ) ; }

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

9-14 ADT Priority Queue Operations Transformers –MakeEmpty –Enqueue –Dequeue Observers –IsEmpty –IsFull change state observe state

9-15 Implementation Level There are many ways to implement a priority queue –An unsorted List- dequeuing would require searching through the entire list –An Array-Based Sorted List- Enqueuing is expensive –A Reference-Based Sorted List- Enqueuing again is 0(N) –A Binary Search Tree- On average, 0(log 2 N) steps for both enqueue and dequeue –A Heap- guarantees 0(log 2 N) steps, even in the worst case

9-16 PQType ~PQType Enqueue Dequeue. [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] ‘X’ ‘C’ ‘J’ Private Data: numItems 3 maxItems 10 items.elements.numElements class PQType

9-17 Class PQType Declaration class FullPQ(){}; class EmptyPQ(){}; template class PQType { public: PQType(int); ~PQType(); void MakeEmpty(); bool IsEmpty() const; bool IsFull() const; void Enqueue(ItemType newItem); void Dequeue(ItemType& item); private: int length; HeapType items; int maxItems; };

9-18 Class PQType Function Definitions template PQType ::PQType(int max) { maxItems = max; items.elements = new ItemType[max]; length = 0; } template void PQType ::MakeEmpty() { length = 0; } template PQType ::~PQType() { delete [] items.elements; }

9-19 Class PQType Function Definitions Dequeue Set item to root element from queue Move last leaf element into root position Decrement length items.ReheapDown(0, length-1) Enqueue Increment length Put newItem in next available position items.ReheapUp(0, length-1)

9-20 Code for Dequeue template void PQType ::Dequeue(ItemType& item) { if (length == 0) throw EmptyPQ(); else { item = items.elements[0]; items.elements[0] = items.elements[length-1]; length--; items.ReheapDown(0, length-1); }

9-21 Code for Enqueue template void PQType ::Enqueue(ItemType newItem) { if (length == maxItems) throw FullPQ(); else { length++; items.elements[length-1] = newItem; items.ReheapUp(0, length-1); }

9-22 Comparison of Priority Queue Implementations EnqueueDequeue HeapO(log 2 N) Linked ListO(N) Binary Search Tree BalancedO(log 2 N) SkewedO(N)

9-23 Definitions Graph: A data structure that consists of a set of models and a set of edges that relate the nodes to each other Vertex: A node in a graph Edge (arc): A pair of vertices representing a connection between two nodes in a graph Undirected graph: A graph in which the edges have no direction Directed graph (digraph): A graph in which each edge is directed from one vertex to another (or the same) vertex

9-24 Formally a graph G is defined as follows: G = (V,E) where V(G) is a finite, nonempty set of vertices E(G) is a set of edges (written as pairs of vertices)

9-25 An undirected graph

9-26 A directed graph

9-27 A directed graph

9-28 More Definitions Adjacent vertices: Two vertices in a graph that are connected by an edge Path: A sequence of vertices that connects two nodes in a graph Complete graph: A graph in which every vertex is directly connected to every other vertex Weighted graph: A graph in which each edge carries a value

9-29 Two complete graphs

9-30 A weighted graph

9-31 Definitions Depth-first search algorithm: Visit all the nodes in a branch to its deepest point before moving up Breadth-first search algorithm: Visit all the nodes on one level before going to the next level Single-source shortest-path algorithm: An algorithm that displays the shortest path from a designated starting node to every other node in the graph

9-32 Array-Based Implementation Adjacency Matrix: for a graph with N nodes, and N by N table that shows the existence (and weights) of all edges in the graph

9-33 Adjacency Matrix for Flight Connections

9-34 Linked Implementation Adjacency List: A linked list that identifies all the vertices to which a particular vertex is connected; each vertex has its own adjacency list

9-35 Adjacency List Representation of Graphs

9-36 ADT Set Definitions Base type: The type of the items in the set Cardinality: The number of items in a set Cardinality of the base type: The number of items in the base type Union of two sets: A set made up of all the items in either sets Intersection of two sets: A set made up of all the items in both sets Difference of two sets: A set made up of all the items in the first set that are not in the second set

9-37 Beware: At the Logical Level Sets can not contain duplicates. Storing an item that is already in the set does not change the set. If an item is not in a set, deleting that item from the set does not change the set. Sets are not ordered.

9-38 Implementing Sets Explicit implementation (Bit vector) Each item in the base type has a representation in each instance of a set. The representation is either true (item is in the set) or false (item is not in the set). Space is proportional to the cardinality of the base type. Algorithms use Boolean operations.

9-39 Implementing Sets (cont.) Implicit implementation (List) The items in an instance of a set are on a list that represents the set. Those items that are not on the list are not in the set. Space is proportional to the cardinality of the set instance. Algorithms use ADT List operations.

9-40 Explain: If sets are not ordered, why is the SortedList ADT a better choice as the implementation structure for the implicit representation?