Priority Queues and Binary Heaps Chapter 6.5 1. 107 - Trees Some animals are more equal than others A queue is a FIFO data structure the first element.

Slides:



Advertisements
Similar presentations
COL 106 Shweta Agrawal and Amit Kumar
Advertisements

Advanced Data Structures Chapter 16. Priority Queues Collection of elements each of which has a priority. Does not maintain a first-in, first-out discipline.
Heapsort.
CMPT 225 Priority Queues and Heaps. Priority Queues Items in a priority queue have a priority The priority is usually numerical value Could be lowest.
Binary Heaps CSE 373 Data Structures Lecture 11. 2/5/03Binary Heaps - Lecture 112 Readings Reading ›Sections
Heapsort. 2 Why study Heapsort? It is a well-known, traditional sorting algorithm you will be expected to know Heapsort is always O(n log n) Quicksort.
Heaps and heapsort COMP171 Fall Sorting III / Slide 2 Motivating Example 3 jobs have been submitted to a printer in the order A, B, C. Sizes: Job.
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
Source: Muangsin / Weiss1 Priority Queue (Heap) A kind of queue Dequeue gets element with the highest priority Priority is based on a comparable value.
1 Chapter 8 Priority Queues. 2 Implementations Heaps Priority queues and heaps Vector based implementation of heaps Skew heaps Outline.
1 Foundations of Software Design Fall 2002 Marti Hearst Lecture 17: Binary Search Trees; Heaps.
CSE 373 Data Structures and Algorithms Lecture 13: Priority Queues (Heaps)
Binary Search Trees Section Trees Trees are efficient Many algorithms can be performed on trees in O(log n) time. Searching for elements.
1 CSC 427: Data Structures and Algorithm Analysis Fall 2010 transform & conquer  transform-and-conquer approach  balanced search trees o AVL, 2-3 trees,
Heapsort Based off slides by: David Matuszek
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
ADT Table and Heap Ellen Walker CPSC 201 Data Structures Hiram College.
Heapsort CSC Why study Heapsort? It is a well-known, traditional sorting algorithm you will be expected to know Heapsort is always O(n log n)
The Binary Heap. Binary Heap Looks similar to a binary search tree BUT all the values stored in the subtree rooted at a node are greater than or equal.
Chapter 11 Heap. Overview ● The heap is a special type of binary tree. ● It may be used either as a priority queue or as a tool for sorting.
Data Structures Week 8 Further Data Structures The story so far  Saw some fundamental operations as well as advanced operations on arrays, stacks, and.
Chapter 21 Priority Queue: Binary Heap Saurav Karmakar.
1 Heaps and Priority Queues Starring: Min Heap Co-Starring: Max Heap.
P p Chapter 10 has several programming projects, including a project that uses heaps. p p This presentation shows you what a heap is, and demonstrates.
CSC 213 – Large Scale Programming Lecture 15: Heap-based Priority Queue.
Priority Queue. Priority Queues Queue (FIFO). Priority queue. Deletion from a priority queue is determined by the element priority. Two kinds of priority.
CSE373: Data Structures & Algorithms Lecture 6: Priority Queues Dan Grossman Fall 2013.
CSE 250 September 29 – October 3, A NNOUNCEMENTS 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.
1 Heaps (Priority Queues) You are given a set of items A[1..N] We want to find only the smallest or largest (highest priority) item quickly. Examples:
Priority Queues and Heaps. October 2004John Edgar2  A queue should implement at least the first two of these operations:  insert – insert item at the.
1 Heaps and Priority Queues v2 Starring: Min Heap Co-Starring: Max Heap.
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.
Queues, Stacks and Heaps. Queue List structure using the FIFO process Nodes are removed form the front and added to the back ABDC FrontBack.
CS 361 – Chapter 5 Priority Queue ADT Heap data structure –Properties –Internal representation –Insertion –Deletion.
CSE373: Data Structures & Algorithms Lecture 6: Priority Queues Kevin Quinn Fall 2015.
Heapsort. What is a “heap”? Definitions of heap: 1.A large area of memory from which the programmer can allocate blocks as needed, and deallocate them.
Lecture 15 Jianjun Hu Department of Computer Science and Engineering University of South Carolina CSCE350 Algorithms and Data Structure.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
1 Heap Sort. A Heap is a Binary Tree Height of tree = longest path from root to leaf =  (lgn) A heap is a binary tree satisfying the heap condition:
Internal and External Sorting External Searching
CS 367 Introduction to Data Structures Lecture 8.
1 Chapter 6 Heapsort. 2 About this lecture Introduce Heap – Shape Property and Heap Property – Heap Operations Heapsort: Use Heap to Sort Fixing 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)
Sorting Cont. Quick Sort As the name implies quicksort is the fastest known sorting algorithm in practice. Quick-sort is a randomized sorting algorithm.
CSE332: Data Abstractions Lecture 4: Priority Queues Dan Grossman Spring 2012.
Heaps, Heap Sort, and Priority Queues. Background: Binary Trees * Has a root at the topmost level * Each node has zero, one or two children * A node that.
Lecture on Data Structures(Trees). Prepared by, Jesmin Akhter, Lecturer, IIT,JU 2 Properties of Heaps ◈ Heaps are binary trees that are ordered.
Priority Queues and Heaps. John Edgar  Define the ADT priority queue  Define the partially ordered property  Define a heap  Implement a heap using.
CSE373: Data Structures & Algorithms Priority Queues
CSE373: Data Structures & Algorithms
October 30th – Priority QUeues
Source: Muangsin / Weiss
Heap Sort Example Qamar Abbas.
Heap Chapter 9 Objectives Upon completion you will be able to:
7/23/2009 Many thanks to David Sun for some of the included slides!
Chapter 8 – Binary Search Tree
Dr. David Matuszek Heapsort Dr. David Matuszek
Binary Tree Application Operations in Heaps
Computer Science 2 Heaps.
Heaps Chapter 11 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates.
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) A heap.
Heapsort.
Priority Queues & Heaps
Priority Queues CSE 373 Data Structures.
Heapsort.
Heaps By JJ Shepherd.
Hash Maps: The point of a hash map is to FIND DATA QUICKLY.
Heapsort.
Heapsort.
CO 303 Algorithm Analysis and Design
Presentation transcript:

Priority Queues and Binary Heaps Chapter 6.5 1

107 - Trees Some animals are more equal than others A queue is a FIFO data structure the first element in is the first element out which of course means the last one in is the last one out But sometimes we want to sort of have a queue but we want to order items according to some characteristic the item has. 2

107 - Trees Priorities We call the ordering characteristic the priority. When we pull something from this “queue” we always get the element with the best priority (sometimes best means lowest). It is really common in Operating Systems to use priority to schedule when something happens. e.g. the most important process should run before a process which isn’t so important data off disk should be retrieved for more important processes first 3

107 - Trees Priority Queue A priority queue always produces the element with the best priority when queried. You can do this in many ways keep the list sorted or search the list for the minimum value (if like the textbook - and Unix actually - you take the smallest value to be the best) You should be able to estimate the Big O values for implementations like this. e.g. O(n) for choosing the minimum value of an unsorted list. There is a clever data structure which allows all operations on a priority queue to be done in O(log n). 4

107 - Trees Binary Heap Actually binary min heap Shape property - a complete binary tree - all levels except the last full. The last level nodes are filled from the left. Heap property - all parents are < or = to their children 5

107 - Trees Cool cleverness Complete binary trees can be represented very nicely in arrays or lists. Because there are no gaps we can represent the rows of the tree as a series of lists which we can then join together into one list

107 - Trees My child is 2 x Me If we add an empty element at the beginning of the list we can then find the left child of any node at position p at 2 x p, and right child at 2 x p + 1. e.g. The children of the element at position 2 are in position 4 and 5. In this case the children of 2 are 17 and

107 - Trees 8

Binary Heap Operations Create an empty binary heap Insert an item in the heap Retrieve the smallest item (removing it) Get the size of the heap Build a heap from a list 9

107 - Trees Create a new binary heap # We could start with something like: class BinHeap: def __init__(self): self.heap_list = [0] # We will develop something better later. # N.B. I don’t keep track of the size as the textbook # does because we can use len(self.heap_list) - 1. def size(self): """Return the size of the heap.""" return len(self.heap_list)

107 - Trees Insert into the heap We want to maintain the two properties the shape property (so the tree stays complete) the heap property (so the smallest value is at the root) The shape property is easy to maintain. We just add the value into the next leaf position of our tree. In the list implementation this means we append the element onto the list. 11

107 - Trees Preserve the heap To keep the heap property we may need to move the new value further up the tree. We repeatedly compare it to its parent exchanging them if it is smaller than its parent. This is sometimes called percolating because the smallest values bubble to the top. 12

107 - Trees 13

107 - Trees Why is the exchange safe? When we are swapping a value with its parent (say we are halfway up the tree) we know that the heap property will still be true for the subtree we are currently looking at because The new value is smaller than its parent and if the other child was greater than or equal to the parent value it must be greater than the new value. Any subtree below the current position of the new value must have values all greater than the parent so they are still in the correct positions. 14

107 - Trees Insertion code def insert(self, k): self.heap_list.append(k) self.perc_up(self.size()) def perc_up(self, i): # we keep comparing with the parent until we reach the top # or the parent is smaller than the child while i // 2 > 0 and self.heap_list[i] < self.heap_list[i // 2]: self.heap_list[i], self.heap_list[i // 2] = \ self.heap_list[i // 2], self.heap_list[i] i = i // 2 15

107 - Trees Getting the minimum value With a min heap this is trivial. It is the root element or in our list implementation the element at index 1. If we remove it we need to fix the shape and heap properties. The shape is easy to fix once again - we move the last leaf in the heap to the first position (or root). 16

107 - Trees Preserving the heap again This time we have almost certainly moved a larger value into the root. We want to percolate this value down the tree. 17

107 - Trees 18

107 - Trees Going down is a little trickier than going up Percolating up was straight-forward because each child only has one parent. Percolating down we want to swap with the smallest child (to preserve the heap property). 19

107 - Trees Deleting code def del_min(self): ret_val = self.heap_list[1] replacement = self.heap_list.pop() if self.size() > 0: self.heap_list[1] = replacement self.perc_down(1) return ret_val 20

107 - Trees Percolating down def perc_down(self, i): while (i * 2) <= self.size(): child = self.min_child(i) if self.heap_list[i] > self.heap_list[child]: self.heap_list[child], self.heap_list[i] = \ self.heap_list[i], self.heap_list[child] i = child def min_child(self, i): ”””Return the index of the minimum child of index i.””” left = i * 2 right = left + 1 if right > self.size(): return left if self.heap_list[left] < self.heap_list[right]: return left else: return right 21

107 - Trees Building a heap from a list We can do it the boring way. Start with an empty list and insert each element in turn. This will be O(n log n) as there are n elements to add and each could percolate up the levels of the tree. Or we can do it the clever way. 22

107 - Trees The Efficient Way We start half way through the list. Any nodes in the last half of the list are leaves because of the shape of our complete binary tree. Each level of the tree has one more node than the sum of the nodes in all previous levels. Moving backwards through the list percolate each element down to its correct position. This is O(n) - but I am not going to prove it :). 23

107 - Trees 24 This is what Figure 6.12 should look like.

107 - Trees Sifting up and down

107 - Trees Building the heap code def __init__(self, a_list=[]): """Constructs a BinHeap object. Can either create an empty BinHeap or can construct it from a_list. """ self.heap_list = [0] + a_list # add the dummy to list for i in range(self.size() // 2, 0, -1): self.perc_down(i) 26

107 - Trees Different heaps but the same outcome bh = BinHeap() bh.insert(9) bh.insert(6) bh.insert(5) bh.insert(2) bh.insert(3) print(bh) bh = BinHeap([9,6,5,2,3]) print(bh) 27 Output [2, 3, 6, 9, 5] [2, 3, 5, 6, 9]

107 - Trees And by the way The BinHeap class has a special __str__ method to print out the heap values but leave out the dummy first element. def __str__(self): return str(self.heap_list[1:]) 28