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.

Slides:



Advertisements
Similar presentations
1 HeapSort CS 3358 Data Structures. 2 Heapsort: Basic Idea Problem: Arrange an array of items into sorted order. 1) Transform the array of items into.
Advertisements

1 Heaps & Priority Queues (Walls & Mirrors - Remainder of Chapter 11)
© 2006 Pearson Addison-Wesley. All rights reserved12 B-1 Chapter 12 (continued) Tables and Priority Queues.
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.
CS 315 March 24 Goals: Heap (Chapter 6) priority queue definition of a heap Algorithms for Insert DeleteMin percolate-down Build-heap.
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
© 2006 Pearson Addison-Wesley. All rights reserved12-1 Chapter 12 Tables and Priority Queues CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring.
A Heap Implementation Chapter Chapter Contents Reprise: The ADT Heap Using an Array to Represent a Heap Adding an Entry Removing the Root Creating.
Binary Heaps What is a Binary Heap? Array representation of a Binary Heap MinHeap implementation Operations on Binary Heaps: enqueue dequeue deleting an.
© 2006 Pearson Addison-Wesley. All rights reserved12 A-1 Chapter 12 Heaps.
Lecture 11 Binary Heap King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
Heaps. 2 A complete binary tree Nodes contain Comparable objects Each node contains no smaller (or no larger) than objects in its descendants Maxheap.
Chapter 12 B Priority Queues. © 2004 Pearson Addison-Wesley. All rights reserved 12 B-2 The ADT Priority Queue: A Variation of the ADT Table The ADT priority.
Analysis of Algorithms CS 477/677 Instructor: Monica Nicolescu.
Fundamentals of Python: From First Programs Through Data Structures
Marc Smith and Jim Ten Eyck
CSE 373 Data Structures and Algorithms Lecture 13: Priority Queues (Heaps)
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.
Compiled by: Dr. Mohammad Alhawarat BST, Priority Queue, Heaps - Heapsort CHAPTER 07.
Computer Science and Software Engineering University of Wisconsin - Platteville 12. Heap Yan Shi CS/SE 2630 Lecture Notes Partially adopted from C++ Plus.
ADT Table and Heap Ellen Walker CPSC 201 Data Structures Hiram College.
CS 1031 Tree Traversal Techniques; Heaps Tree Traversal Concept Tree Traversal Techniques: Preorder, Inorder, Postorder Full Trees Almost Complete Trees.
© 2011 Pearson Addison-Wesley. All rights reserved 11 B-1 Chapter 11 (continued) Trees.
1 Trees A tree is a data structure used to represent different kinds of data and help solve a number of algorithmic problems Game trees (i.e., chess ),
data ordered along paths from root to leaf
Chapter 21 Priority Queue: Binary Heap Saurav Karmakar.
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.
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.
The ADT Table The ADT table, or dictionary Uses a search key to identify its items Its items are records that contain several pieces of data 2 Figure.
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.
Lecture 8 : Priority Queue Bong-Soo Sohn Assistant Professor School of Computer Science and Engineering Chung-Ang University.
Chapter 12 Heaps & HeapSort © John Urrutia 2014, All Rights Reserved1.
Binary Search Trees (BST)
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”
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.
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:
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.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
CS 367 Introduction to Data Structures Lecture 8.
CSI 312 Dr. Yousef Qawqzeh Heaps and Priority Queue.
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)
Priority Queues and Heaps. John Edgar  Define the ADT priority queue  Define the partially ordered property  Define a heap  Implement a heap using.
Tables and Priority Queues
Priority Queues and Heaps
Bohyung Han CSE, POSTECH
Binary Trees, Binary Search Trees
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
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.
original list {67, 33,49, 21, 25, 94} pass { } {67 94}
CS Data Structures Chapter 17 Heaps Mehmet H Gunes
CS Data Structures Chapter 17 Heaps Mehmet H Gunes
Hassan Khosravi / Geoffrey Tien
Ch. 12 Tables and Priority Queues
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Sorting Dr. Yingwu Zhu.
Heaps By JJ Shepherd.
CO4301 – Advanced Games Development Week 4 Binary Search Trees
Chapter 12 Heap ADT © 2011 Pearson Addison-Wesley. All rights reserved.
EE 312 Software Design and Implementation I
Heaps.
Presentation transcript:

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 position retrieval of an item - complexity is: O(n) insertion of an item - for random insertion, the complexity is, in the worst case, O(n). 2) Binary Search Tree sort by value retrieval of an item - complexity O(log n) for each item, O(n*log n) for n items insertion of an item - O(log n) for each item, O(n*log n) for n items 3) Priority Queues sort by value retrieval of an item - complexity can be constant: O(1) insertion of an item - requires searching algorithms for finding correct position in the Queue

Course: Programming II - Abstract Data Types HeapsSlide Number 2 An alternative way of sorting Heaps are complete binary trees that provide an alternative way of sorting a collection of elements. Different heaps can be defined according to the sorting: Minheaps: Heaps where the the smallest element is at the root Maxheaps: Heaps where the the largest element is at the root How does a heap differ from a binary search tree?  It is always a complete binary tree  ordering: a binary search tree can be viewed as a fully sorted set, a heap contains a weaker ordering of the elements.

Course: Programming II - Abstract Data Types HeapsSlide Number 3 Definition  The ADT Heap (or maxheap) is a complete binary tree in which the value at the root of the tree is greater than or equal to the values of both its children; and both sub-trees are heaps. A heap can also be empty.  The element with the largest value is at the root of the tree. This kind of heap is called maxheap.  Retrieving the element with the highest priority would mean returning the root of the tree. How well does this data structure implement a priority queue?

Course: Programming II - Abstract Data Types HeapsSlide Number 4 Access Procedures add(newElem) // post: adds newElem into a heap in its proper position. // post: throws exception if heap is full. removeMax( ) //post: if heap is not empty, returns the element in the root of the heap and deletes it //post: from the heap. If heap is empty, returns null. Additional auxiliary procedures to helps us restructure the heap: heapRebuild(root) //pre: takes a semi-heap (both subtrees are heaps but root element may not be bigger //pre: than both its children). //post: transforms the tree into a heap. createHeap() // post: create an empty heap. isEmpty() // post: returns true if the heap is empty, false otherwise. getMax() // post: retrieves the largest element in the heap, returns null if the heap is empty.

Course: Programming II - Abstract Data Types HeapsSlide Number 5 Heap Interface for the ADT Heap public interface Heap >{ public boolean isEmpty(); //Post: Returns true if the heap is empty, otherwise returns false. public void add(T newElem) throws HeapException; //Pre: newElem is the new element to be inserted //Post: If insertion is successful, newElem is added to the heap at the correct place. //post: Throws HeapException if the element cannot be added to the heap. public T removeMax( ); //Post: If heap is not empty, the element with maximum value is returned and //Post: deleted from the heap. If heap is empty, it returns null. public T getMax( ); //Post: If heap is not empty, the element with maximum value is returned. //Post: If heap is empty, it returns null. }

Course: Programming II - Abstract Data Types HeapsSlide Number 6 Implementation of the ADT Heap Since a heap is a complete binary tree, we can have an efficient static implementation using arrays: Next node The parent of a node(i) is at node (i-1)/2 Children of node(i) are at node(2i+1) and node(2i+2) As the tree is complete, data is always in consecutive nodes from node 0. We also need to keep track of the last node (or next available space in the array). Size of the array = number of elements

Course: Programming II - Abstract Data Types HeapsSlide Number 7 Beginning the class MaxHeap public class MaxHeap > implements Heap { private T[] heap; private int lastIndex; private static final int defaultInitialCapacity = 25; public MaxHeap( ){ heap = (T[]) new Comparable[defaultInitialCapacity]; lastIndex = 0; } public T getMax(){ T root = null; if (!isEmpty()) root = heap[0]; return root; } public void add(T newItem) throws HeapException{ } public T removeMax(){ } } public boolean isEmpty() { return (lastIndex == 0); }

Course: Programming II - Abstract Data Types HeapsSlide Number 8 Removing max element: the basic idea  Retrieving the element with maximum value means retrieving the root of the tree.  Removing the element with maximum value gives two sub-heaps. How can we rejoin the two sub-heaps into a single heap? The simplest way is to take the rightmost node in the tree and put it at the root: This is a semi-heap: a complete binary tree, whose left and right sub-trees are both heaps, but with the root node out of place in the ordering. We would therefore need to convert it back to a heap

Course: Programming II - Abstract Data Types HeapsSlide Number 9 Converting a semi-heap into a heap 1. Compare the value in the root with the values of its children, 2. If either child’s value is larger than the root, exchange the root with the larger of the two children’s values. 3. If there is no exchange, the tree is a heap. Otherwise (i.e. the previous root, now a child, may still be misplaced) repeat steps 1 and 2 until no exchange is necessary, or leaf nodes are reached After each element removal we restructure the tree into a valid heap. After the restructuring, the largest value remains at the root, ready for output:

Course: Programming II - Abstract Data Types HeapsSlide Number 10 The heapRebuild auxiliary procedure heapRebuild(root) //post: Converts a semiheap rooted at index “root” into a heap. Recursively trickles the element at //post: index “root” down to its proper position by swapping it with its larger child, if the child is larger //post: than the element. If the element is a leaf, nothing needs to be done. if (the root is not a leaf) { // root must have a left child child = 2 * root +1 // standard index value for a left child node in static // implementation. if (the root has a right child) { rightChild = child +1 // index value of right child in the static implementation if (heap[rightChild] > heap[child]) child = rightChild; // this is the larger child index. } if (heap[root] < heap[child]) { Swap heap[root] and heap[child] heapRebuild(child) //transform semi-heap rooted at child into a heap} } } // else case: root is a leaf, so we are done.

Course: Programming II - Abstract Data Types HeapsSlide Number 11 The delete access procedure T removeMax( ){ T rootElem = heap[0]; heap[0] = heap[lastIndex-1]; lastIndex--; heapRebuild(0); return rootElem; } Efficiency: Removing an element requires us to swap array elements. How many array elements do we have to swap, at most? The method heapRebuild needs at most 3 * log 2 (n) reference changes So, removeMax( ) is O(log 2 n), which is quite efficient.

Course: Programming II - Abstract Data Types HeapsSlide Number 12 Adding an element: the basic idea add The tree is complete, but 65 is in the wrong place – we must restructure the heap: The strategy is the opposite of that for delete( ): 1. Insert new element at the bottom of the tree 2. Trickles the new element up to its proper place.

Course: Programming II - Abstract Data Types HeapsSlide Number 13 Efficiency of add To trickle an element up the tree is easier. We know that the parent of a node [i] is always at position [(i-1)/2]. So no recursion is needed How many array elements do we have to change, at most? add(newElem) is also O(log 2 n) We still trickle the element up along a single path. We need at most 3 * log 2 (n+1) reference changes.

Course: Programming II - Abstract Data Types HeapsSlide Number 14 HeapSort Efficient sorting algorithm using a heap: (i) Convert the data to be sorted into a heap (ii) Sorting the new array heap, so as to be in incremental order n-10 anArray (heap) (ii) n-10 anArray (sorted) E.g.: Sorting a given array: n-10 anArray (given) (i)

Course: Programming II - Abstract Data Types HeapsSlide Number 15 Converting an array into a heap Heapsort(anArray, n){ // build initial heap for (index = n-1 down to 0) //assert: the tree rooted at index is a semiheap heapRebuild(anArray, index, n) //assert: the tree rooted at index is a heap pseudocode:

Course: Programming II - Abstract Data Types HeapsSlide Number 16 HeapSorting the array Heap (1) At the beginning, the sorted region is empty and the heap region is equal to the entire array. The array is partitioned into two regions: the heap region and the sorted region. 0last HeapSorted (largest elements in array) n-1last+1 At an arbitrary iteration array[0..last] is the heap region (left still to sort) and array[last+1..n-1] is the sorted region. In particular the sorted region will contain the largest elements of the array. Invariant: After step k, the Sorted region contains the k largest values in the initial Heap, and they are in sorted order: Array[n-1] is the largest, …. The elements in the heap region form a Heap.

Course: Programming II - Abstract Data Types HeapsSlide Number 17 //sort the heap array last = n-1 //invariant: Array[0..last] is a heap, Array[last+1..n-1] is sorted for (step = 1 through n-1) { Swap Array[0] and Array[last] Decrement last heapRebuild(anArray, 0, last) } HeapSorting the array Heap (2) pseudocode:

Course: Programming II - Abstract Data Types HeapsSlide Number 18 0last Swap and last last0 heapRebuild 1) swapping [0] with [5], last = 4, and heapRebuild(array,0,4) last0 Swap and last last0 heapRebuild 2) swapping [0] with [4], last = 3, and heapRebuild(array,0,3) last0 Swap and last last0 heapRebuild 3) swapping [0] with [3], last = 2, and heapRebuild(array,0,2) last0 Swap and last last0 heapRebuild 4) swapping [0] with [2], last = 1, and heapRebuild(array,0,1) last Swap and last last heapRebuild 5) swapping [0] with [1], last = 0, and heapRebuild(array,0,0). 0n Array Heap Trace of HeapSort, beginning with:

Course: Programming II - Abstract Data Types HeapsSlide Number 19 Summary Heaps are particular types of binary trees extremely useful for inserting, and deleting sorted elements. The tree is full except possibly for the lowest level. When we know the maximum number of elements stored at any time, array- based implementation is the best heap implementation, useful also to implement priority queues. Heapsort is an efficient sorting algorithm, useful for sorting arrays.

Course: Programming II - Abstract Data Types Hash TablesSlide Number 20 Conclusion What is an Abstract Data Type Introduce individual ADTs Understand the data type abstractly Define the specification of the data type Use the data type in small applications, basing solely on its specification Implement the data type Static approach Dynamic approach Some fundamental algorithms for some ADTs: pre-order, in-order and post-order traversal, heapsort Lists Stacks Queues Trees Heaps AVL Trees Red-Black Trees

Course: Programming II - Abstract Data Types Hash TablesSlide Number 21