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.

Slides:



Advertisements
Similar presentations
COL 106 Shweta Agrawal and Amit Kumar
Advertisements

1 CSC 427: Data Structures and Algorithm Analysis Fall 2004 Heaps and heap sort  complete tree, heap property  min-heaps & max-heaps  heap operations:
CS 315 March 24 Goals: Heap (Chapter 6) priority queue definition of a heap Algorithms for Insert DeleteMin percolate-down Build-heap.
Binary Heaps CSE 373 Data Structures Lecture 11. 2/5/03Binary Heaps - Lecture 112 Readings Reading ›Sections
Heaps CS 308 – Data Structures.
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
CS 261 – Data Structures Priority Queues & Heaps.
1 Chapter 8 Priority Queues. 2 Implementations Heaps Priority queues and heaps Vector based implementation of heaps Skew heaps Outline.
CSE 373 Data Structures and Algorithms Lecture 13: Priority Queues (Heaps)
1 BST Trees A binary search tree is a binary tree in which every node satisfies the following: the key of every node in the left subtree is.
1 CSC 427: Data Structures and Algorithm Analysis Fall 2010 transform & conquer  transform-and-conquer approach  balanced search trees o AVL, 2-3 trees,
CSC 172 DATA STRUCTURES. Priority Queues Model Set with priorities associatedwith elements Priorities are comparable by a < operator Operations Insert.
Maps A map is an object that maps keys to values Each key can map to at most one value, and a map cannot contain duplicate keys KeyValue Map Examples Dictionaries:
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
Priority Queues and Heaps Bryce Boe 2013/11/20 CS24, Fall 2013.
Heaps and Priority Queues CS 3358 – Data Structures.
PRIORITY QUEUES (HEAPS). Queues are a standard mechanism for ordering tasks on a first-come, first-served basis However, some tasks may be more important.
ADT Table and Heap Ellen Walker CPSC 201 Data Structures Hiram College.
Sorting with Heaps Observation: Removal of the largest item from a heap can be performed in O(log n) time Another observation: Nodes are removed in order.
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.
Priority Queues and Binary Heaps Chapter Trees Some animals are more equal than others A queue is a FIFO data structure the first element.
Chapter 21 Binary Heap.
data ordered along paths from root to leaf
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.
Data Structures Balanced Trees 1CSCI Outline  Balanced Search Trees 2-3 Trees Trees Red-Black Trees 2CSCI 3110.
1 Heaps and Priority Queues Starring: Min Heap Co-Starring: Max Heap.
Topic 24 Heaps "You think you know when you can learn, are more sure when you can write even more when you can teach, but certain when you can program."
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.
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.
COSC2007 Data Structures II Chapter 12 Tables & Priority Queues III.
1 Joe Meehean.  We wanted a data structure that gave us... the smallest item then the next smallest then the next and so on…  This ADT is called a priority.
Priority Queues and Heaps. October 2004John Edgar2  A queue should implement at least the first two of these operations:  insert – insert item at the.
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.
Lecture 15 Jianjun Hu Department of Computer Science and Engineering University of South Carolina CSCE350 Algorithms and Data Structure.
Chapter 12 Heaps & HeapSort © John Urrutia 2014, All Rights Reserved1.
Prof. Amr Goneid, AUC1 Analysis & Design of Algorithms (CSCE 321) Prof. Amr Goneid Department of Computer Science, AUC Part R3. Priority Queues.
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 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:
CS 367 Introduction to Data Structures Lecture 8.
Priority Queues and Heaps Data Structures and Algorithms CS 244 Brent M. Dingle, Ph.D. Department of Mathematics, Statistics, and Computer Science University.
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)
Heaps CS 302 – Data Structures Sections 8.8, 9.1, and 9.2.
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.
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.
Priority Queues and Heaps. John Edgar  Define the ADT priority queue  Define the partially ordered property  Define a heap  Implement a heap using.
Priority Queues and Heaps Tom Przybylinski. Maps ● We have (key,value) pairs, called entries ● We want to store and find/remove arbitrary entries (random.
Heaps and Heap Sort. Sorting III / Slide 2 Background: Complete Binary Trees * A complete binary tree is the tree n Where a node can have 0 (for the leaves)
"Teachers open the door, but you must enter by yourself. "
CSCE 210 Data Structures and Algorithms
Priority Queues and Heaps
Bohyung Han CSE, POSTECH
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
ADT Heap data structure
- Alan Perlis Heaps "You think you know when you can learn,
original list {67, 33,49, 21, 25, 94} pass { } {67 94}
Chapter 8 – Binary Search Tree
Wednesday, April 18, 2018 Announcements… For Today…
Tree Representation Heap.
Hassan Khosravi / Geoffrey Tien
"Teachers open the door, but you must enter by yourself. "
Tables and Priority Queues
Priority Queues & Heaps
Heaps By JJ Shepherd.
CO4301 – Advanced Games Development Week 4 Binary Search Trees
Priority Queue and Heap
Presentation transcript:

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 first or highest first The highest priority item is removed first Priority queue operations Insert Remove in priority queue order (not a FIFO!)

6 5 4 Using a Priority Queue 3 2 1

Implementing a Priority Queue Items have to be removed in priority order This can only be done efficiently if the items are ordered in some way A balanced binary search (e.g., red-black) tree is an efficient and ordered data structure but Some operations (e.g. removal) are complex to code Although operations are O(log n) they require quite a lot of structural overhead There is another binary tree solution – heaps Note: We will see that search/removal of the maximum element is efficient, but it’s not true for other elements

Heaps A heap is binary tree with two properties Heaps are complete All levels, except the bottom, must be completely filled in The leaves on the bottom level are as far to the left as possible. Heaps are partially ordered (“heap property”): The value of a node is at least as large as its children’s values, for a max heap or The value of a node is no greater than its children’s values, for a min heap

Complete Binary Trees complete binary trees incomplete binary trees

Partially Ordered Tree – max heap Note: an inorder traversal would result in: 9, 13, 10, 86, 44, 65, 23, 98, 21, 32, 17, 41, 29

Priority Queues and Heaps A heap can be used to implement a priority queue Because of the partial ordering property the item at the top of the heap must always the largest value Implement priority queue operations: Insertions – insert an item into a heap Removal – remove and return the heap’s root For both operations preserve the heap property

Heap Implementation Heaps can be implemented using arrays There is a natural method of indexing tree nodes Index nodes from top to bottom and left to right as shown on the right (by levels) Because heaps are complete binary trees there can be no gaps in the array

Array implementations of heap public class Heap { private int HEAPSIZE=200; // max. number of elements in the heap private T items[]; // array of heap items private int num_items; // number of items public Heap() { items = new T[HEAPSIZE]; num_items=0; } // end default constructor We could also use a dynamic array implementation to get rid of the limit on the size of heap. We will assume that priority of an element is equal to its key. So the elements are partially sorted by their keys. They element with the biggest key has the highest priority.

Referencing Nodes It will be necessary to find the indices of the parents and children of nodes in a heap’s underlying array The children of a node i, are the array elements indexed at 2i+1 and 2i+2 The parent of a node i, is the array element indexed at floor[(i–1)/2]

Helping methods private int parent(int i) { return (i-1)/2; } private int left(int i) { return 2*i+1; } private int right(int i) { return 2*i+2; }

Heap Array Example index value Heap: Underlying Array:

Heap Insertion On insertion the heap properties have to be maintained; remember that A heap is a complete binary tree and A partially ordered binary tree There are two general strategies that could be used to maintain the heap properties Make sure that the tree is complete and then fix the ordering, or Make sure the ordering is correct first Which is better?

Heap Insertion algorithm The insertion algorithm first ensures that the tree is complete Make the new item the first available (left-most) leaf on the bottom level i.e. the first free element in the underlying array Fix the partial ordering Repeatedly compare the new value with its parent, swapping them if the new value is greater than the parent (for a max heap) Often called “bubbling up”, or “trickling up”

Heap Insertion Example index value Insert 81

Heap Insertion Example index value Insert (13-1)/2 = is less than 98 so we are finished

Heap Insertion algorithm public void insert(T newItem) { // TODO: should check for the space first num_items++; int child = num_items-1; while (child > 0 && item[parent(child)].getKey() < newItem.getKey()) { items[child] = items[parent(child)]; child = parent(child); } items[child] = newItem; }

Heap Removal algorithm Make a temporary copy of the root’s data Similar to the insertion algorithm, ensure that the heap remains complete Replace the root node with the right-most leaf on the last level i.e. the highest (occupied) index in the array Repeatedly swap the new root with its largest valued child until the partially ordered property holds Return the root’s data

Heap Removal Example index value Remove root

Heap Removal Example index value Remove root 17 children of root: 2*0+1, 2*0+2 = 1, left child is greater replace root with right-most leaf ??

Heap Removal Example index value Remove root children: 2*1+1, 2*1+2 = 3, 4 right child is greater ??

1744 index value Heap Removal Example Remove root 17 children: 2*4+1, 2*4+2 = 9, 10 left child is greater ??

Heap Removal algorithm public T remove() // remove the highest priority item { // TODO: should check for empty heap T result = items[0]; // remember the item T item = items[num_items-1]; num_items--; int current = 0; // start at root while (left(current) < num_items) { // not a leaf // find a bigger child int child = left(current); if (right(current) < num_items && items[child].getKey() < items[right(current)].getKey()) { child = right(current); } if (item.getKey() < items[child].getKey()) { items[current] = items[child]; current = child; } else break; } items[current] = item; return result; }

Heap Efficiency For both insertion and removal the heap performs at most height swaps For insertion at most height comparisons For removal at most height*2 comparisons The height of a complete binary tree is given by  log 2 (n)  +1 Both insertion and removal are O(logn) Remark: but removal is only implemented for the element with the highest key!