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.

Slides:



Advertisements
Similar presentations
COL 106 Shweta Agrawal and Amit Kumar
Advertisements

Heaps1 Part-D2 Heaps Heaps2 Recall Priority Queue ADT (§ 7.1.3) A priority queue stores a collection of entries Each entry is a pair (key, value)
Chapter 4: Trees Part II - AVL Tree
PRIORITY QUEUES AND HEAPS Lecture 19 CS2110 Spring
Fundamentals of Python: From First Programs Through Data Structures
Trees Chapter 8.
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.
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
Binary Heaps CSE 373 Data Structures Lecture 11. 2/5/03Binary Heaps - Lecture 112 Readings Reading ›Sections
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
FALL 2006CENG 351 Data Management and File Structures1 External Sorting.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L12 (Chapter 20) Lists, Stacks,
Tirgul 7 Heaps & Priority Queues Reminder Examples Hash Tables Reminder Examples.
Priority Queues1 Part-D1 Priority Queues. Priority Queues2 Priority Queue ADT (§ 7.1.3) A priority queue stores a collection of entries Each entry is.
Week 10: Heap and Priority queue. Any feature here?
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:
Heapsort Based off slides by: David Matuszek
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
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.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Chapter 19 Implementing Trees and Priority Queues Fundamentals of Java.
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 6 Binary Trees. 6.1 Trees, Binary Trees, and Binary Search Trees Linked lists usually are more flexible than arrays, but it is difficult to use.
Chapter 21 Binary Heap.
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.
Priority Queue. Priority Queues Queue (FIFO). Priority queue. Deletion from a priority queue is determined by the element priority. Two kinds of priority.
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:
Chapter 2: Basic Data Structures. Spring 2003CS 3152 Basic Data Structures Stacks Queues Vectors, Linked Lists Trees (Including Balanced Trees) Priority.
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.
1 Heaps and Priority Queues v2 Starring: Min Heap Co-Starring: Max Heap.
Data Structure II So Pak Yeung Outline Review  Array  Sorted Array  Linked List Binary Search Tree Heap Hash Table.
Data Structures Chapter 6. Data Structure A data structure is a representation of data and the operations allowed on that data. Examples: 1.Array 2.Record.
PRIORITY QUEUES AND HEAPS Slides of Ken Birman, Cornell University.
Queues, Stacks and Heaps. Queue List structure using the FIFO process Nodes are removed form the front and added to the back ABDC FrontBack.
Heaps and Heapsort Prof. Sin-Min Lee Department of Computer Science San Jose State University.
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 and basic data structures David Kauchak cs161 Summer 2009.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
AVL Trees and Heaps. AVL Trees So far balancing the tree was done globally Basically every node was involved in the balance operation Tree balancing can.
Mergeable Heaps David Kauchak cs302 Spring Admin Homework 7?
Quotes “From each according to his ability, to each according to his needs” -- Karl Marx/Queue ADT “In America, first you get the sugar, then you get the.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
HeapSort 25 March HeapSort Heaps or priority queues provide a means of sorting: 1.Construct a heap, 2.Add each item to it (maintaining the heap.
CS 367 Introduction to Data Structures Lecture 8.
Heaps © 2010 Goodrich, Tamassia. Heaps2 Priority Queue ADT  A priority queue (PQ) stores a collection of entries  Typically, an entry is a.
"Teachers open the door, but you must enter by yourself. "
Chapter 12 – Data Structures
Chapter 11 Heap.
Heaps (8.3) CSE 2011 Winter May 2018.
Priority Queues © 2010 Goodrich, Tamassia Priority Queues 1
Heaps © 2010 Goodrich, Tamassia Heaps Heaps
Bohyung Han CSE, POSTECH
Heap Sort Example Qamar Abbas.
ADT Heap data structure
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}
Part-D1 Priority Queues
Binary Tree Application Operations in Heaps
Ch. 8 Priority Queues And Heaps
Hassan Khosravi / Geoffrey Tien
Priority Queues & Heaps
Priority Queues CSE 373 Data Structures.
Presentation transcript:

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.

Learning Objectives ● Learn how the heap can play the role of a priority queue. ● Describe the structure and ordering properties of the heap. ● Study the characteristic heap operations, and analyze their running time. ● Understand the public interface of a heap class. ● Design a heap-based priority scheduler.

Learning Objectives ● Develop a priority scheduling package in Java that uses the heap class. ● Implement the heap class using an array list as the storage component for the heap entries. ● Appreciate the software engineering issues that inform the design of an updatable heap.

11.1 Heap as Priority Queue ● In a priority queue, the heap acts as a data structure in which the entries have different priorities of removal.  The entry with the highest priority is the one that will be removed next. ● A FIFO queue may be considered a special case of a priority queue, in which the priority of an entry is the time of its arrival in the queue, and the earlier the arrival time, the higher the priority.

11.1 Heap as Priority Queue ● The emergency room in a hospital is a quintessential priority queue. ● Scheduling different processes in an operating system.  Processes arrive at different points of time, and take different amounts of time to finish executing.  The operating system needs to ensure that all processes get fair treatment in the amount of CPU time they are allocated. No single process should hog the CPU nor should any process starve for CPU time.

11.1 Heap as Priority Queue ● A crucial difference between the ER example and the CPU scheduling application  The priority of this patient must be increased according to the severity of his or her condition.  An ER-like situation is best represented by a priority queue model in which the priority of an entry may change while it is in the queue. ● We will focus on heaps that do not allow for the priority of an existing entry to be changed.

11.2 Heap Properties

● Remember, a complete binary tree is one in which every level but the last must have the maximum number of nodes possible at that level.  The last level may have fewer than the maximum possible nodes, but they should be arranged from left to right without any empty spots. ● A complete binary tree is called the heap structure property. ● The relative ordering among the keys is called the heap ordering property.

11.2 Heap Properties

Max and Min Heaps ● A max heap  The maximum key is at the top of the heap.

Max and Min Heaps ● A priority queue can be implemented either as a max heap or a min heap, according to whether a greater key indicates greater priority (max heap) or smaller priority (min heap).

11.3 Heap Operations ● The insert operation inserts a new entry in the heap. ● The delete operation that removes the entry at the front of the priority queue.

Insert ● Inserting a new key in a heap must ensure that after insertion, both the heap structure and the heap ordering properties are satisfied.  Insert the new key so that the heap structure property is satisfied, i.e. the new tree after insertion is also complete.  Make sure that the heap ordering property is satisfied by sifting up the newly inserted key.

Insert

● Sifting up

Delete ● Deletion removes the entry at the top of the heap. ● This leaves a vacant spot at the root, and the heap has to be restored.

Delete ● The key k that is extracted from the last node and written into the root is moved as far down as needed. ● The children of k are first compared with each other to determine the larger key.  If k is smaller, it is exchanged with the larger key. ● This process continues until either the larger of the keys of k’s children is less than or equal to k, or k reaches a leaf node.

Delete

Running Time Alanysis ● Worst Case  Assume that the last level contains the full compliment of nodes.  h = log( n + 1 ) - 1

Running Time Analysis ● Insert  Worst case: the new key may be sifted all the way up to the root.  O(log n) ● Delete  Worst case: the key may be sifted all the way down to a leaf node.  O(log n)

11.4 A Heap Class

● The heap accepts items of any type with the restriction that the type implements the compareTo method of the Comparable interface. ● first returns the top of the heap, and every subsequent call to next returns the item that would appear next in a level-order traversal going top to bottom.

11.5 Priority Scheduling with Heap ● A processor and a queue of schedulable processes that are waiting for their turn at the processor. ● The processes are given relative priorities of execution so that the process with the highest priority in the process queue is the first one to be executed when the processor is free.

11.5 Priority Scheduling with Heap ● The process with the highest priority in the heap is sent to the CPU for execution at time t.

A Scheduling Package using Heap

● If two processors have the same priority value, the earlier arrival time gets higher priority.

11.6 Sorting with the Heap Class ● Imagine the priority queue operates in two distinct phases.  "outlet" is shut off (build phase) ● entries are allowed to come in but not allowed to exit.  "inlet" is shut off (sort phase) ● no entry is allowed in, and all the resident entries are let out one by one based on priority. ● The entries have been sorted according to priority order.

Example: Sorting Integers

● The build phase is a sequence of n calls to the add method of the Heap class. ● Adding the i-th element takes up to log i time in the worst case.

Example: Sorting Integers ● Stirling's formula

Example: Sorting Integers ● The sort phase is O(n log n) ● O(n log n) + O(n log n) = O(n log n)

11.7 Heap Class Implementation ● The heap is a special type of binary tree.  A complete one. ● The heap entries can be stored in an array.

Array Storage

● Determining the parent and the children of each node  For a node of the binary tree at index k, its left and right children are at indices 2k + 1 and 2k + 2, respectively.  The parent of a node at index k is at index (k – 1)/2.

Array Storage ● For a node at index k, if 2k + 1 is beyond the upper limit of the array, the node is a leaf. ● If a node at index k has a child at 2k + 2, then there must be a child at 2k + 1. ● Finding a parent or a child is O(1).

Array Storage ● It is possible to implement any binary tree as an array.

Array Storage

Implementation using ArrayList

● What happens when a new item is added, and the arrayList is full to capacity?  The array will be resized in order to accommodate the new item.  If the heap had n items including the new item, the resizing is O(n).  Resizing should happen very infrequently, especially if the initial capacity is assigned carefully.

Designing an Updatable Heap ● In order to update an entry, one would first have to locate it in the heap. ● If a heap had n entries, it would take up to O(n) time to find that entry.

Handles to heap entries ● We need a direct pointer to that entry so we avoid searching. ● O(1) to find, and O(log n) to update.

Handles to heap entries ● How is the client informed that the handle of 8 and 5 have changed?

Shared handle array ● The heap maintains a separate handle array, and shares this array with the clients

Shared handle array

Encapsulating handles within heap ● Encapsulating the handle array within the heap insulates the client program space from the heap, while ensuring that handles are always fresh. ● When an item is added, the handle that is returned is an index into the handle array, instead of a location in the heap array list.

Encapsulating handles within heap ● Whenever an item is added to the heap, it is assigned a new handle by growing the handle array.

Encapsulating handles within heap ● The size of the handle array is equal to the number of items ever added to the heap. ● If n items are added to the heap but there are never more than k items in the heap at any time, the original heap (of the Heap class) would have required exactly k units of space. ● Our updatable heap requires n + k units of space.

Recycling free handle space ● We must carefully recycle space in the handle array. ● When an item is deleted from the heap, it no longer needs space in the handle array.  The client will never access this item again. ● This space can be marked available so when a new item is added to the heap, it may be reused as a handle to this new item.

Recycling free handle space ● Since we cannot afford to spend time searching in the handle array for such marked, recyclable space, we need to have a separate data structure that will keep track of all free spaces. ● A simple data structure that will achieve this is a list or a stack.

Recycling free handle space ● Whenever an item is to be added to the heap, the free-space stack is first checked to see if it is not empty. ● If so, the top entry of the stack is popped–this entry would contain the index of a free position in the handle array.  The new item’s handle would be in this position. ● If the free space stack is empty, the new item’s handle would be added as a new handle entry at the end of the handle array.

Recycling free handle space ● The new item itself is always added at the end of the heap array list. ● The client is passed back the index in the handle array where the new item’s handle has been stored.

Recycling free handle space ● An updatable heap will support update of keys in O(log n) time, since every update results in either a sift up or a sift down. ● It would ensure that the amount of space used is O(m) where m is the maximum number of items ever in the heap.

11.9 Summary ● A heap is a complete binary tree with the property that the value of the item at any node x is greater than or equal to the values of the items at all the nodes in the subtree rooted at x. ● The above defines a max heap. A min heap is defined symmetrically–the heap ordering property now requires that the value at a node be less than or equal to the values at the nodes in its subtree.

11.9 Summary ● A heap may be used as a priority queue. It may also be used to sort a set of values. ● One of the important uses of a priority queue is in scheduling a set of activities in order of their priorities. ● The entries of a heap are stored in an array for maximum effectiveness in space usage. ● The (max) heap operations delete max and insert both take O(log n) time.

11.9 Summary ● The heap data structure does not support a fast search operation. ● The updatable heap support update of keys in O(log n) time, and uses O(m) space, where m is the maximum number of items ever in the heap.