1 HEAPS & PRIORITY QUEUES Array and Tree implementations.

Slides:



Advertisements
Similar presentations
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)
Advertisements

 Chapter 11 has several programming projects, including a project that uses heaps.  This presentation shows you what a heap is, and demonstrates two.
CS 206 Introduction to Computer Science II 03 / 23 / 2009 Instructor: Michael Eckmann.
Priority Queues. 2 Priority queue A stack is first in, last out A queue is first in, first out A priority queue is least-first-out The “smallest” element.
Priority Queue and Heap 1. 2 Priority Queue ADT A priority queue stores a collection of entries Each entry is a pair (key, value) Main methods of the.
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.
Trees II Kruse and Ryba Ch 10.1,10.2,10.4 and 11.3.
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.
CS 206 Introduction to Computer Science II 11 / 04 / 2009 Instructor: Michael Eckmann.
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
Priority Queues. Priority queue A stack is first in, last out A queue is first in, first out A priority queue is least-first-out –The “smallest” element.
Priority Queues. Priority queue A stack is first in, last out A queue is first in, first out A priority queue is least-first-out –The “smallest” element.
PQ, binary heaps G.Kamberova, Algorithms Priority Queue ADT Binary Heaps Gerda Kamberova Department of Computer Science Hofstra University.
Trees Main and Savitch Chapter 10. Binary Trees A binary tree has nodes, similar to nodes in a linked list structure. Data of one sort or another may.
1 Foundations of Software Design Fall 2002 Marti Hearst Lecture 17: Binary Search Trees; Heaps.
CSC 172 DATA STRUCTURES. Priority Queues Model Set with priorities associatedwith elements Priorities are comparable by a < operator Operations Insert.
Heapsort Based off slides by: David Matuszek
Computer Science and Software Engineering University of Wisconsin - Platteville 12. Heap Yan Shi CS/SE 2630 Lecture Notes Partially adopted from C++ Plus.
9/17/20151 Chapter 12 - Heaps. 9/17/20152 Introduction ► Heaps are largely about priority queues. ► They are an alternative data structure to implementing.
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.
Priority Queues and Binary Heaps Chapter Trees Some animals are more equal than others A queue is a FIFO data structure the first element.
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 Queues Dr. David Matuszek
Priority Queue. Priority Queues Queue (FIFO). Priority queue. Deletion from a priority queue is determined by the element priority. Two kinds of priority.
PRIORITY QUEUES AND HEAPS CS16: Introduction to Data Structures & Algorithms Tuesday, February 24,
Chapter 2: Basic Data Structures. Spring 2003CS 3152 Basic Data Structures Stacks Queues Vectors, Linked Lists Trees (Including Balanced Trees) 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.
1 Heaps and Priority Queues v2 Starring: Min Heap Co-Starring: Max Heap.
CSC211 Data Structures Lecture 18 Heaps and Priority Queues Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College.
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.
Week 13 - Friday.  What did we talk about last time?  Sorting  Insertion sort  Merge sort  Started quicksort.
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.
INTRO TO HEAP & Adding and Removing a NODE Presented to: Sir AHSAN RAZA Presented by: SHAH RUKH Roll #07-22 Semester BIT 3 rd Session 2007—2011 Department.
CSC212 Data Structure Lecture 16 Heaps and Priority Queues Instructor: George Wolberg Department of Computer Science City College of New York.
1 Heaps A heap is a binary tree. A heap is best implemented in sequential representation (using an array). Two important uses of heaps are: –(i) efficient.
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”
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:
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.
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.
Week 13 - Wednesday.  What did we talk about last time?  NP-completeness.
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)
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.
Heaps (8.3) CSE 2011 Winter May 2018.
Heaps 8/2/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser,
Heaps © 2010 Goodrich, Tamassia Heaps Heaps
i206: Lecture 14: Heaps, Graphs intro.
Priority Queues.
Tree Representation Heap.
CSC212 Data Structure - Section AB
Heaps Chapter 10 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates two.
Heaps Chapter 10 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates two.
Heaps Chapter 11 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates.
Heaps Chapter 11 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates.
Heaps © 2014 Goodrich, Tamassia, Goldwasser Heaps Heaps
Priority Queues.
Priority Queues.
Heaps Chapter 10 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates two.
Heaps.
CS210- Lecture 13 June 28, 2005 Agenda Heaps Complete Binary Tree
Presentation transcript:

1 HEAPS & PRIORITY QUEUES Array and Tree implementations

2 Priority queue A stack is first in, last out A queue is first in, first out A priority queue is least-first-out The “smallest” element is the first one removed

3 The definition of “smallest” is up to the programmer (for example, you might define it by implementing Comparator or Comparable )

4 Priority queue If there are several “smallest” elements, the implementer must decide which to remove first Remove any “smallest” element (don’t care which) Remove the first one added

5 A priority queue is an: ADT where items are removed based on their priority (highest-to-lowest), regardless of the order they ARE inserted in the structure

6 A priority queue ADT PriorityQueue(): Methods void add(Comparable o): void add(Comparable o): inserts o into the priority queue Comparable removeLeast(): Comparable removeLeast(): removes and returns the least element Comparable getLeast(): Comparable getLeast(): returns (but does not remove) the least element isEmpty(): boolean isEmpty(): returns true iff empty int size(): int size(): returns the number of elements void clear(): void clear(): discards all elements

7 Evaluating implementations When we choose a data structure, usage patterns it is important to look at usage patterns If we load an array once and do thousands of searches on it, we want to make searching fast— so we would probably sort the array

8 When we choose a data structure, it is important to look at usage patterns few searches If we load a huge array and expect to do only a few searches, we probably don’t want to spend time sorting the array

9 Evaluating implementations uses of a queue (including a priority queue), For almost all uses of a queue (including a priority queue), remove everything that we add we eventually remove everything that we add

10 TIMING Hence, analyze a priority queue, when we analyze a priority queue, neither “add” nor “remove” is more important— timing for we need to look at the timing for (“add + remove”)

11 Array implementations A priority queue could be implemented as an unsorted array (with a count of elements) Adding an element would take O(1) time (why?) Removing an element would take O(n) time (why?) Hence, (adding and removing) an element takes O(n) time inefficient representation This is an inefficient representation – a BigO(N)

12 Array implementations A priority queue could be implemented as a sorted array (again, with a counter of elements) Adding an element would take O(n) time (why?) Removing an element would take O(1) time (why?) So adding and removing) an element takes O(n) time Again, this is very inefficient

13 Linked list implementations A priority queue could be implemented as an – unsorted linked list O(1) Adding an element would take O(1) time (why?) Removing an element would take (N) time (why?) Again, inefficient!

14 SORTED LINKED LIST A priority queue could be implemented as a sorted linked list Adding an element Adding an element would take O(n) time (why?) Removing an element Removing an element would take O(1) time (why?) inefficient algorithm Again, an inefficient algorithm

15 Binary tree implementations A priority queue could be represented as a – balanced binary search tree Insertion and removal could destroy the balance We would need an algorithm to rebalance the binary tree Good rebalancing algorithms O(log n) time complicated Good rebalancing algorithms require O(log n) time, but are complicated

16 Heap Implementaton The concepts of heaps is used to refer to memory in a computer, E.g. the part of the memory that provides dynamic memory allocation ( get it as you need it) “Heap” is also used as a name for a special kind of binary tree

17 Heap is a complete binary tree A heap is a complete binary tree with values stored in its nodes such that no child has a value bigger than the value of its parent – (though it can be equal)

18 Therefore we would like to find a better algorithm. We want to: Insert and Remove with a Big O of one

19 HEAPS & Priority Queues A binary tree represented as a heap facilitates the operation to find the maximum element: “it is always in the root of the tree “ Because finding the node with the maximum value in a heap is a BigO(I) A HEAP is the most efficient structure for implementing priority queues

20 HeapsHeaps A heap is a certain kind of complete binary tree. When a complete binary tree is built, its first node must be the root. When a complete binary tree is built, its first node must be the root. Root

21 HeapsHeaps Complete binary tree. Right child The Second and third Nodes are always the left and right child of the root. The Second and third Nodes are always the left and right child of the root. Left child

22 HeapsHeaps Complete binary tree. The next nodes always fill the next left-to-right. level from left-to-right. The next nodes always fill the next left-to-right. level from left-to-right.

23 HeapsHeaps Complete binary tree.

24 HeapsHeaps A heap is a certain kind of complete binary tree. Each node in a heap contains a key that can be compared to other nodes' keys. Each node in a heap contains a key that can be compared to other nodes' keys

25 To implement a heap as a priority queue A node has the heap property if it is Equal to or greater than as its children OR ( since smaller numbers represent higher priorities) if it is smaller than or equal to its children ( since smaller numbers represent higher priorities) Heap: Yellow node has the heap property Priority queue: Yellow node has the heap property - less than its children

26 Heaps A heap is a certain kind of complete binary tree. This example is a max heap. The "heap property" requires that each node's key is >= to the keys of its children The "heap property" requires that each node's key is >= to the keys of its children

27 Priority Queues A heap can easily implement a priority queue remove the element of highest priority? but what happens with we remove the element of highest priority? How do we re-arrange the tree?

28 Removing from a heap There are two things we need to consider when rearranging : We want to end up with a heap which means that The tree has to be complete – ALL HEAPS ARE COMPLETE TREES!

29 To remove an element at top of tree : Remove the element at location 0 to location 0, decrement Move the element in the lastIndex to location 0, decrement lastIndex (lastIndex is at the end of the heap) Reheap the new root node Reheap the new root node (the one now at location 0 ) down-heap bubbling or percolating down This is called down-heap bubbling or percolating down Down-heap bubbling Down-heap bubbling requires O(log n) time to remove an element

30 Removing the Top of a Heap (max heap) ¶Move the last node onto the root

31 Removing the Top of a Heap (max heap) ¶Move the value in the last node into the root

32 Removing the Top of a Heap ¶Move the last node onto the root. ·Push the out-of-place node downward, ·swapping with its larger child ·until the new node reaches an acceptable location

33 Removing the Top of a Heap ¶Move the last node onto the root. ·Push the out-of-place node downward, acceptable location. ·Push the out-of-place node downward, swapping with its larger child until the new node reaches an acceptable location

34 Removing the Top of a Heap ¶Move the last node onto the root. ·Push the out-of-place node downward, swapping with its larger child until the new node reaches an acceptable location. ·Note that we discard half of the tree with each move downward

reheapification downward. We stop when: keys <= to the out-of- place node, or The children all have keys <= to the out-of- place node, or The node reaches the leaf. The node reaches the leaf. The process of pushing the node downward is called: reheapification downward

36 Priority Queues Another Example : How to delete a node from a Priority Queue Since it is queue - first in first out, we remove the first one The Root

37 An Example of a MAX Heap The root has largest value

38 Deleting a node from the heap a heap priority queue We use a heap to implement a priority queue next" element ( the root the "next" element ( the root ) in the queue was removed (pop operation). We end up with a root with no value Root has no value

39 Deleting a node from the heap The obvious question is: which node can we use to replace this one? The obvious question is: which node can we use to replace this one?

40 Deleting a node from the heap If we want this tree to stay complete the rightmost element in the bottommost level is the obvious choice If we want this tree to stay complete the rightmost element in the bottommost level is the obvious choice

41 Deleting a node from the heap We now have a problem: We have a complete tree but this is not a heap! WHY??? This can be solved by applying systematic swap of nodes. We now have a problem: We have a complete tree but this is not a heap! WHY??? This can be solved by applying systematic swap of nodes.

42 Deleting a node from the heap We systematically swap the root with the larger of the children nodes until no more swaps can be done We systematically swap the root with the larger of the children nodes until no more swaps can be done

43 Deleting a node from the heap

44 Deleting a node from the heap

45 Deleting a node from the heap The tree has restored its heap property! The tree has restored its heap property!

46 Insert operation Another example - the heap below Recall that while delete causes pairwise swaps from the root to the bottom, insert causes pairwise swaps from the bottom to the top. insert an element with value 20 Suppose that we want to insert an element with value

47 insert (20)

48 insert (20)

49 insert (20)

50 insert (20)

51 Implementing a Heap We will store the data from the nodes in a partially-filled array. An array of data

52 Implementing a Heap Data from the root goes in the first location of the array. An array of data

53 Implementing a Heap Data from the next row goes in the next two array locations. An array of data

54 Implementing a Heap Data from the next row goes in the next two array locations. An array of data

55 Implementing a Heap Data from the next row goes in the next two array locations. An array of data

56 Points about the Implementation The links between the tree's nodes are not actually stored as pointers, or in any other way. manipulate the data. The only way we "know" that "the array is a tree" is from the way we manipulate the data. An array of data

57 Array representation of a heap Left child of node i is 2*i + 1, right child is 2*i + 2 lastIndex Unless the value is larger than lastIndex -therefore no such child Parent of node i is (i – 1)/2 unless i == lastIndex = location 5

58 algorithm for the array implementation new value where lastIndex now references -- Increase lastIndex and put the new value where lastIndex now references -- that is add to the end of the array Reheap Reheap the newly added node up-heap bubbling or percolating This is called up-heap bubbling or percolating up Up-heap bubbling requires O(log n) time Adding to heap - - Implementation

59 Points about the Implementation If you know the index of a node, then it is easy to figure out the indexes of that node's parent and children. [0] [0] [1] [2] [3] [4]

60 Points about the Implementation If we add 45 to the tree and to the array, 45’s parent is at what index? i = ? (i-1)/2 = 2 [0] [0] [1] [2] [3] [4] [5]

61 Points about the Implementation If we add 45 to the tree and the array, 45’s parent is at what index? (i-1)/2 which is 2. We do a comparison of 45 with its parent and swap if it is greater than the parent - it is greater than it [0] [0] [1] [2] [3] [4] [5]

62 Points about the Implementation If we add 45 to the tree and to the tree and the array, 45’s parent is at what index? (i-1)/2 which is 2. We do a comparison and swap. It is still out of place. [0] [0] [1] [2] [3] [4] [5]

63 Points about the Implementation 45 is still out of place, so we do another comparison and swap with 45’s parent which is 42. So what is the terminating condition)(s)? [0] [0] [1] [2] [3] [4] [5]

64 A heap is a complete binary tree, where the entry at each node is greater than or equal to the entries in its children. OR the entry at each node is less than or equal to the entries in its children. Summary

65 Summary Adding/Deleting To add an entry to a heap, place the new entry at the next available spot, and perform a reheapification upward. To remove the biggest entry, move the value in the last node onto the root, and perform a reheapification downward.

66 Reheapifying a Tree Fine, we know how to delete one element and restore the heap, but there are several other operations involving heaps

67 If we find a systematic way of heapifying a tree, we could perform any operation because we can execute the procedure heapify

68 Reheapifying a Tree heapify a tree using a quite simple idea. we can heapify a tree using a quite simple idea. Given a binary tree T (not necessarily a heap) with root R and left subtree T left and T right, if these two subtrees are heaps, if these two subtrees are heaps, we can make T a heap using the process described in the previous slide (of applying systematic swaps) We start the process of heapifying a tree from the lower levels

69 Algorithm for Reheapifying Tree The algorithm aims at heapifying a tree by always comparing three nodes at a time. To start from the lower levels we choose to look at the internal nodes in reverse level order reverse level order External nodes have no children so they are (individually) heaps

70 HEAPIFY void heapify (Heap h) { NodeType n; NodeType n; for (n = the internal nodes of h in reverse level- order) { for (n = the internal nodes of h in reverse level- order) { Reheapify the heap h starting at node n Reheapify the heap h starting at node n }} void heapify (Heap h) { NodeType n; NodeType n; for (n = the internal nodes of h in reverse level- order) { for (n = the internal nodes of h in reverse level- order) { Reheapify the heap h starting at node n Reheapify the heap h starting at node n }}

Let change this tree into a heap - A MAX HEAP

72 An example Internal Nodes in Reverse Level-Order are: 1, 12, 17, 4, 6, start with the leftmost leaf : compare 3 To 1

and 1 have swapped 3 and 1 have swapped Internal Nodes in Reverse Level-Order: 3, 12, 17, 4, 6

74 An example Compare 12 with its children and swap 12 and 22 : Compare 12 with its children and swap 12 and 22 : Internal Nodes in Reverse Level-Order: 3, 22, 17, 4, 6

75 An example Compare 17 with its children and no changes necessary: 3, 22, 17, 4, NEXT COMPARE 4 AND 22

Compare 22 with 4 and swap : 4 IS NOW OUT OF PLACE

77 An example Compare 12 and 4 and swap, NEXT compare 22 to 6 : 3, 12, 17, 22, 6

Heapify 6 downwards until it finds its proper location : 3, 12, 17, 6

Reheap down 6 : Compare 6 and 11

80 An example is in place and the tree is reheaped:

81 An example

82heapsort Heapsort is another algorithm for sorting lists The idea behind heap sort is that to sort a list we can insert the elements of a list into a heap using heapify Then remove all the elements using remove.

83 The idea behind heap sort is that to sort a list we can insert the elements of a list into a heap using heapify Then remove all the elements using remove. largest element is removed first, It is guaranteed that the largest element is removed first, So by systematically removing the elements we get the list ordered ( in reverse order)