Heaps and priority queues

Slides:



Advertisements
Similar presentations
COL 106 Shweta Agrawal and Amit Kumar
Advertisements

Comp 122, Spring 2004 Binary Search Trees. btrees - 2 Comp 122, Spring 2004 Binary Trees  Recursive definition 1.An empty tree is a binary tree 2.A node.
AVL Trees1 Part-F2 AVL Trees v z. AVL Trees2 AVL Tree Definition (§ 9.2) AVL trees are balanced. An AVL Tree is a binary search tree such that.
Transform and Conquer Chapter 6. Transform and Conquer Solve problem by transforming into: a more convenient instance of the same problem (instance simplification)
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Binary Trees Chapter 6. Linked Lists Suck By now you realize that the title to this slide is true… By now you realize that the title to this slide is.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Sorting Chapter Sorting Consider list x 1, x 2, x 3, … x n We seek to arrange the elements of the list in order –Ascending or descending Some O(n.
BST Data Structure A BST node contains: A BST contains
Gordon College Prof. Brinton
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 19 Binary.
Sorting Chapter 13 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved
10. Binary Trees A. Introduction: Searching a linked list.
Binary Search Trees Chapter 6.
Heapsort Based off slides by: David Matuszek
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
Compiled by: Dr. Mohammad Alhawarat BST, Priority Queue, Heaps - Heapsort CHAPTER 07.
Searching: Binary Trees and Hash Tables CHAPTER 12 6/4/15 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,
Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Searching:
Adapted from instructor resource slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All.
Sorting. Pseudocode of Insertion Sort Insertion Sort To sort array A[0..n-1], sort A[0..n-2] recursively and then insert A[n-1] in its proper place among.
2-3 Tree. Slide 2 Outline  Balanced Search Trees 2-3 Trees Trees.
Binary Search Tree vs. Balanced Search Tree. Why care about advanced implementations? Same entries, different insertion sequence: 10,20,30,40,50,60,70,
Sorting Chapter Sorting Consider list x 1, x 2, x 3, … x n We seek to arrange the elements of the list in order –Ascending or descending Some O(n.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Sorting.
1 10. Binary Trees Read Sec A. Introduction: Searching a linked list. 1. Linear Search /* Linear search a list for a particular item */ 1. Set.
Sorting Dr. Yingwu Zhu. Heaps A heap is a binary tree with properties: 1. It is complete Each level of tree completely filled Except possibly bottom level.
COSC2007 Data Structures II Chapter 12 Tables & Priority Queues III.
Priority Queues and Heaps. October 2004John Edgar2  A queue should implement at least the first two of these operations:  insert – insert item at the.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use at Midwestern State University Chapter.
Search: Binary Search Trees Dr. Yingwu Zhu. Linear Search Collection of data items to be searched is organized in a list x 1, x 2, … x n Assume == and.
Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.
Chapter 13 Priority Queues. 2 Priority queue A stack is first in, last out A queue is first in, first out A priority queue is least-in-first-out The “smallest”
COSC 2007 Data Structures II Chapter 13 Advanced Implementation of Tables I.
Sorting Dr. Yingwu Zhu. Heaps A heap is a binary tree with properties: 1. It is complete Each level of tree completely filled Except possibly bottom level.
Search: Binary Search Trees Dr. Yingwu Zhu. Review: Linear Search Collection of data items to be searched is organized in a list x 1, x 2, … x n – Assume.
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.
Sorting Cont. Quick Sort As the name implies quicksort is the fastest known sorting algorithm in practice. Quick-sort is a randomized sorting algorithm.
Priority Queues and Heaps. John Edgar  Define the ADT priority queue  Define the partially ordered property  Define a heap  Implement a heap using.
TCSS 342, Winter 2006 Lecture Notes
AA Trees.
Searching and Binary Search Trees
UNIT III TREES.
Lecture 22 Binary Search Trees Chapter 10 of textbook
Heap Sort Example Qamar Abbas.
ITEC 2620M Introduction to Data Structures
ADT Heap data structure
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Function and class templates
Description Given a linear collection of items x1, x2, x3,….,xn
7/23/2009 Many thanks to David Sun for some of the included slides!
original list {67, 33,49, 21, 25, 94} pass { } {67 94}
Searching: Binary Trees
Trees Chapter 15 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved
Tree Representation Heap.
A Robust Data Structure
Final Review Dr. Yingwu Zhu.
Adapted from instructor resource slides
Sorting Dr. Yingwu Zhu.
Yan Shi CS/SE 2630 Lecture Notes
CO4301 – Advanced Games Development Week 4 Binary Search Trees
Instructor: Dr. Michael Geiger Spring 2019 Lecture 34: Exam 3 Preview
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Instructor: Dr. Michael Geiger Spring 2017 Lecture 36: Exam 3 Preview
Instructor: Dr. Michael Geiger Spring 2017 Lecture 30: Sorting & heaps
Instructor: Dr. Michael Geiger Spring 2017 Lecture 33: Hash tables
Heapsort.
EE 312 Software Design and Implementation I
Presentation transcript:

Heaps and priority queues EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019 Lecture 32: Binary trees Heaps and priority queues

Data Structures: Lecture 28 Lecture outline Announcements/reminders Program 4 due 5/1 Program 5 due 5/9 (extra credit) Today’s lecture Recursion Binary search trees 6/5/2019 Data Structures: Lecture 28

Data Structures: Lecture 28 Justifying trees Linked data structures efficiently use space Easier to dynamically grow/shrink than array-based structures Array-based structures are easier to search efficiently Linked lists require linear search Arrays (if sorted) can use binary search Trees: linked structures that can be searched in binary manner 6/5/2019 Data Structures: Lecture 28

Data Structures: Lecture 28 Binary Search Tree Consider the following ordered list of integers Examine middle element Examine left, right sublist (maintain pointers) (Recursively) examine left, right sublists 80 66 62 49 35 28 13 6/5/2019 Data Structures: Lecture 28

Data Structures: Lecture 28 Binary Search Tree Redraw the previous structure so that it has a treelike shape – a binary tree 6/5/2019 Data Structures: Lecture 28

Data Structures: Lecture 28 Trees A data structure which consists of a finite set of elements called nodes or vertices a finite set of directed arcs which connect the nodes If the tree is nonempty one of the nodes (the root) has no incoming arc every other node can be reached by following a unique sequence of consecutive arcs 6/5/2019 Data Structures: Lecture 28

Data Structures: Lecture 28 Trees Tree terminology Root node Children of the parent (3) Siblings to each other Leaf nodes 6/5/2019 Data Structures: Lecture 28

Data Structures: Lecture 28 Binary Trees Each node has at most two children Useful in modeling processes where a comparison or experiment has exactly two possible outcomes the test is performed repeatedly Example Multiple coin tosses Decision trees where each decision is yes/no (example: guessing game) 6/5/2019 Data Structures: Lecture 28

Linked Representation of Binary Trees Uses space more efficiently Provides additional flexibility Each node has two links one to the left child of the node one to the right child of the node if no child node exists for a node, the link is set to NULL 6/5/2019 Data Structures: Lecture 28

Linked Representation of Binary Trees Example 6/5/2019 Data Structures: Lecture 28

Data Structures: Lecture 28 Recursion Recursive functions call themselves A recursive function has two parts Anchor / base case: function value is defined for one or more specific argument values Inductive / recursive case: function value for current argument value defined in terms of previously defined function values and/or arguments Example: Recursive power function double power(double x, unsigned n){ if (n == 0) return 1.0; else return x * power(x, n – 1); } 6/5/2019 Data Structures: Lecture 28

Data Structures: Lecture 24 Common recursive uses Use if, on each iteration, problem splits into 2 or more similar tasks Don’t want to repeat work Graph/tree traversal Will see this with binary trees Divide and conquer algorithms Search, sort algorithms very common examples Think about binary search Test value at midpoint of array If higher than value you’re searching for, test lower half If lower than value you’re searching for, test upper half 6/5/2019 Data Structures: Lecture 24

Binary Trees as Recursive Data Structures A binary tree is either empty … or Consists of a node called the root root has pointers to two disjoint binary (sub)trees called … right (sub)tree left (sub)tree Anchor Inductive step Which is either empty … or … Which is either empty … or … 6/5/2019 Data Structures: Lecture 28

Tree Traversal is Recursive The "anchor" If the binary tree is empty then do nothing Else N: Visit the root, process data L: Traverse the left subtree R: Traverse the right subtree The inductive step 6/5/2019 Data Structures: Lecture 28

ADT Binary Search Tree (BST) Collection of Data Elements binary tree each node x, value in left child of x ≤ value in x ≤ in right child of x Basic operations Construct an empty BST Determine if BST is empty Search BST for given item 6/5/2019 Data Structures: Lecture 28

ADT Binary Search Tree (BST) Basic operations (continued) Insert a new item in the BST Maintain the BST property Delete an item from the BST Traverse the BST Visit each node exactly once The inorder traversal must visit the values in the nodes in ascending order 6/5/2019 Data Structures: Lecture 28

Data Structures: Lecture 28 BST Searches Search begins at root If that is desired item, done If item is less, move down left subtree If item searched for is greater, move down right subtree If item is not found, we will run into an empty subtree 6/5/2019 Data Structures: Lecture 28

Problem of Lopsidedness Tree can be balanced each node except leaves has exactly 2 child nodes 6/5/2019 Data Structures: Lecture 28

Problem of Lopsidedness Trees can be unbalanced not all nodes have exactly 2 child nodes 6/5/2019 Data Structures: Lecture 28

Problem of Lopsidedness Trees can be totally lopsided Suppose each node has a right child only Degenerates into a linked list Processing time affected by "shape" of tree 6/5/2019 Data Structures: Lecture 28

Data Structures: Lecture 29 Balanced trees Solutions to lopsidedness problem: balance tree as you insert/remove data AVL trees Red/black trees 6/5/2019 Data Structures: Lecture 29

Data Structures: Lecture 30 Heaps A heap is a binary tree with properties: It is complete Each level of tree completely filled Except possibly bottom level (nodes in left most positions) It satisfies heap-order property Data in each node >= data in children 6/5/2019 Data Structures: Lecture 30

Data Structures: Lecture 30 Heaps Which of the following are heaps? Only A B isn’t complete—left subtree missing node C doesn’t satisfy heap-order property—6 < 8 A B C 6/5/2019 Data Structures: Lecture 30

Data Structures: Lecture 30 Implementing a Heap Use an array or vector Number the nodes from top to bottom Number nodes on each row from left to right Store data in ith node in ith location of array (vector) 6/5/2019 Data Structures: Lecture 30

Data Structures: Lecture 30 Implementing a Heap Note the placement of the nodes in the array Entry 0 in array kept empty to allow space in array to copy element for sorting 6/5/2019 Data Structures: Lecture 30

Data Structures: Lecture 30 Implementing a Heap In an array implementation children of ith node are at myArray[2*i] and myArray[2*i+1] Parent of the ith node is at myArray[i/2] 6/5/2019 Data Structures: Lecture 30

Data Structures: Lecture 30 Basic Heap Operations Constructor Set mySize to 0, allocate array Empty Check value of mySize Retrieve max item Return root of the binary tree, myArray[1] 6/5/2019 Data Structures: Lecture 30

Basic Heap Operations Delete max item Max item is the root, replace with last node in tree Then interchange root with larger of two children Continue this with the resulting sub-tree(s) Result called a semiheap 6/5/2019 Data Structures: Lecture 30

Percolate Down Algorithm 1. Set c = 2 * r // r = current node, // c = left child 2. While r <= n do following a. If c < n and myArray[c] < myArray[c + 1] Increment c by 1 b. If myArray[r] < myArray[c] i. Swap myArray[r] and myArray[c] ii. set r = c iii. Set c = 2 * c else Terminate repetition End while 6/5/2019 Data Structures: Lecture 30

Data Structures: Lecture 30 Basic Heap Operations Insert an item Amounts to a percolate up routine Place new item at end of array Interchange with parent so long as it is greater than its parent 6/5/2019 Data Structures: Lecture 30

Data Structures: Lecture 30 Heapsort Given a list of numbers in an array Stored in a complete binary tree Convert to a heap Begin at last node not a leaf Apply percolate down to this subtree Continue 6/5/2019 Data Structures: Lecture 30

Data Structures: Lecture 30 Heapsort Algorithm for converting a complete binary tree to a heap – called "heapify" For r = n/2 down to 1: Apply percolate_down to the subtree in myArray[r] , … myArray[n] End for Puts largest element at root 6/5/2019 Data Structures: Lecture 30

Data Structures: Lecture 30 Heapsort Now swap element 1 (root of tree) with last element This puts largest element in correct location Use percolate down on remaining sublist Converts from semi-heap to heap 6/5/2019 Data Structures: Lecture 30

Data Structures: Lecture 30 Heapsort Again swap root with rightmost leaf Continue this process with shrinking sublist 6/5/2019 Data Structures: Lecture 30

Data Structures: Lecture 30 Heapsort Algorithm 1. Consider x as a complete binary tree, use heapify to convert this tree to a heap 2. for i = n down to 2: a. Interchange x[1] and x[i] (puts largest element at end) b. Apply percolate_down to convert binary tree corresponding to sublist in x[1] .. x[i-1] 6/5/2019 Data Structures: Lecture 30

Data Structures: Lecture 28 Final notes Next time: More on binary trees Reminders: Program 4 due 5/1 Program 5 due 5/9 (extra credit) 6/5/2019 Data Structures: Lecture 28

Data Structures: Lecture 28 Acknowledgements These slides are adapted from slides provided with the course textbook: Larry Nyhoff, ADTs, Data Structures, and Problem Solving with C++, 2nd edition, 2005, Pearson/Prentice Hall. ISBN: 0-13-140909-3 6/5/2019 Data Structures: Lecture 28