Heaps. 2 A complete binary tree Nodes contain Comparable objects Each node contains no smaller (or no larger) than objects in its descendants Maxheap.

Slides:



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

CS Section 600 CS Section 002 Dr. Angela Guercio Spring 2010.
A Binary Search Tree Implementation Chapter Chapter Contents Getting Started An Interface for the Binary Search Tree Duplicate Entries Beginning.
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.
1 Heaps & Priority Queues (Walls & Mirrors - Remainder of Chapter 11)
1 CSC 427: Data Structures and Algorithm Analysis Fall 2004 Heaps and heap sort  complete tree, heap property  min-heaps & max-heaps  heap operations:
COMP5712 Tutorial 4. 2 Using an Array to Represent a Heap When a binary tree is complete – Can use level-order traversal to store data in consecutive.
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.
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.
1 TCSS 342, Winter 2005 Lecture Notes Priority Queues and Heaps Weiss Ch. 21, pp
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.
Binary Heaps What is a Binary Heap? Array representation of a Binary Heap MinHeap implementation Operations on Binary Heaps: enqueue dequeue deleting an.
Transforming Infix to Postfix
Lecture 11 Binary Heap King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
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.
Dr. Andrew Wallace PhD BEng(hons) EurIng
sorting31 Sorting III: Heapsort sorting32 A good sorting algorithm is hard to find... Quadratic sorting algorithms (with running times of O(N 2 ), such.
Heapsort CIS 606 Spring Overview Heapsort – O(n lg n) worst case—like merge sort. – Sorts in place—like insertion sort. – Combines the best of both.
1 Binary Heaps What is a Binary Heap? Array representation of a Binary Heap MinHeap implementation Operations on Binary Heaps: enqueue dequeue deleting.
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,
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
data ordered along paths from root to leaf
1 Heaps and Priority Queues Starring: Min Heap Co-Starring: Max Heap.
Priority Queues Dr. David Matuszek
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.
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.
CS187 - Spring 2008 Lecture 19 Searching and Sorting Announcements - Program 5 now due Monday!! Sorting is chapter 10 in textbook.
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.
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.
A Heap Implementation Chapter 26 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Chapter 12 Heaps & HeapSort © John Urrutia 2014, All Rights Reserved1.
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.
CSE 373: Data Structures and Algorithms Lecture 11: Priority Queues (Heaps) 1.
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.
1 Chapter 6 Heapsort. 2 About this lecture Introduce Heap – Shape Property and Heap Property – Heap Operations Heapsort: Use Heap to Sort Fixing heap.
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.
Binary Heaps What is a Binary Heap?
Binary Heaps What is a Binary Heap?
Binary Heaps What is a Binary Heap?
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.
Priority Queues.
Binary Tree Application Operations in Heaps
Priority Queues.
Priority Queues.
CS Data Structures Chapter 17 Heaps Mehmet H Gunes
CS Data Structures Chapter 17 Heaps Mehmet H Gunes
Ch. 12 Tables and Priority Queues
Copyright ©2012 by Pearson Education, Inc. All rights reserved
A Heap Implementation Chapter 26 Adapted from Pearson Education, Inc.
A Heap Implementation Chapter 26 Adapted from Pearson Education, Inc.
Sorting Dr. Yingwu Zhu.
Priority Queues.
CS 367 – Introduction to Data Structures
Priority Queues.
Chapter 12 Heap ADT © 2011 Pearson Addison-Wesley. All rights reserved.
Chapter 9 The Priority Queue ADT
EE 312 Software Design and Implementation I
Presentation transcript:

Heaps

2 A complete binary tree Nodes contain Comparable objects Each node contains no smaller (or no larger) than objects in its descendants Maxheap Object in a node is ≥ its descendant objects Minheap Object in a node is ≤ descendant objects Note contrast of uses of the word "heap" The ADT heap The heap from which memory is allocated (by the OS) when new executes

3 Heaps (a) maxheap and (b) minheap containing the same values Consider how to use a heap to implement a priority queue…

4 The ADT Heap Interface used for implementation of maxheap public interface MaxHeapInterface { public void add(Comparable newEntry); public Comparable removeMax(); public Comparable getMax(); public boolean isEmpty(); public int getSize(); public void clear(); } // end MaxHeapInterface

5 Using an Array to Represent a Heap (a) A complete binary tree with its nodes numbered in level order; (b) its representation as an array.

6 Using an Array to Represent a Heap When a binary tree is complete Can use level-order traversal to store data in consecutive locations of an array Enables easy location of the data in a node's parent or children Parent of a node at i is found at i/2 (unless i is 1) Children of node at i found at indices 2i and 2i + 1

7 public class MaxHeap implements MaxHeapInterface, java.io.Serializable { private Comparable[ ] heap; // array of heap entries private static final int DEFAULT_MAX_SIZE = 25; private int lastIndex;// index of last entry //****************************************************************** public MaxHeap( ) { heap = new Comparable[DEFAULT_MAX_SIZE]; lastIndex = 0; } //****************************************************************** public MaxHeap(int maxSize) { heap = new Comparable[maxSize]; lastIndex = 0; } //****************************************************************** public Comparable getMax( ) { Comparable root = null; if (!isEmpty()) root = heap[1]; return root; } //****************************************************************** public boolean isEmpty( ) { return lastIndex < 1; } //****************************************************************** public int getSize( ) { return lastIndex; } //****************************************************************** public void clear( ) { for (; lastIndex > -1; lastIndex--) heap[lastIndex] = null; lastIndex = 0; } //******************************************************************... Beginning class MaxHeap

8 Adding an Entry The steps in adding 85 to a maxheap

9 Adding an Entry Begin at next available position for a leaf Follow path from this leaf toward root until correct position for new entry is found As this is done Move entries from parent to child Makes room for new entry

10 Adding an Entry Revision of the previous example that avoids swaps.

11 Adding an Entry Array representation of steps in the example

12 Adding an Entry Array representation of steps in the example (continued)

13 Adding an Entry Algorithm for adding new entry to a heap public void add(Comparable newEntry) { lastIndex++; if (lastIndex >= heap.length) doubleArray(); // expand array int newIndex = lastIndex; int parentIndex = newIndex/2; while ( (newIndex > 1) && newEntry.compareTo(heap[parentIndex]) > 0) { heap[newIndex] = heap[parentIndex]; newIndex = parentIndex; parentIndex = newIndex/2; } heap[newIndex] = newEntry; }

14 Removing the Root Steps to remove the entry in root of the previous maxheap

15 Removing the Root Steps that transform a semiheap (i.e., a heap, except for the root) into a heap without swaps.

16 Removing the Root To remove a heap's root Replace the root with heap's last child This forms a semiheap Then use the method reheap Transforms the semiheap to a heap

17 private void reheap(int rootIndex) { boolean done = false; Comparable orphan = heap[rootIndex]; int largerChildIndex = 2*rootIndex; // index of left child, if any while (!done && (largerChildIndex <= lastIndex) ) { int rightChildIndex = largerChildIndex + 1; if ( (rightChildIndex <= lastIndex) && heap[rightChildIndex].compareTo(heap[largerChildIndex]) > 0) { largerChildIndex = rightChildIndex; } if (orphan.compareTo(heap[largerChildIndex]) < 0) { heap[rootIndex] = heap[largerChildIndex]; rootIndex = largerChildIndex; largerChildIndex = 2*rootIndex; // index of next left child } else done = true; } heap[rootIndex] = orphan; }

18 public Comparable removeMax() { Comparable root = null; if (!isEmpty()) { root = heap[1]; // return value heap[1] = heap[lastIndex]; // form a semiheap lastIndex--; // decrease size reheap(1); // transform to a heap } // end if return root; } // end removeMax

19 Creating a Heap The steps in adding 20, 40, 30, 10, 90, and 70 to a heap using add().

20 Creating a Heap The steps in creating a heap by using reheap. More efficient to use reheap than to use add

21 public MaxHeap(Comparable[] entries) { lastIndex = entries.length; heap = new Comparable[lastIndex + 1]; // copy given array to data field for (int index = 0; index < entries.length; index++) heap[index+1] = entries[index]; // create heap for (int index = heap.length/2; index > 0; index--) reheap(index); } Another Constructor for Class MaxHeap Note: entries in array start at 0; entries in heap start at 1

22 Heapsort Possible to use a heap to sort an array Place array items into a maxheap Then remove them Items will be in descending order Place them back into the original array and they will be in order (but requires additional storage)

23 Heapsort A trace of heapsort (first steps…)

24 Heapsort A trace of heapsort (continued)

25 Heapsort A trace of heapsort (continued)

26 Heapsort A trace of heapsort (continued)

27 Heapsort Implementation of heapsort public static void heapSort(Comparable[] array, int n) { // create first heap for (int rootIndex = n/2-1; rootIndex >= 0; rootIndex--) reheap(array, rootIndex, n-1); swap(array, 0, n-1); for (int lastIndex = n-2; lastIndex > 0; lastIndex--) { reheap(array, 0, lastIndex); swap(array, 0, lastIndex); } } private static void reheap(Comparable[] heap, int rootIndex, int lastIndex) { // Similar to statements from previous code. See next page…... } What is the efficiency?

28 Heapsort Implementation of heapsort public static void heapSort(Comparable[] array, int n) { // create first heap for (int rootIndex = n/2-1; rootIndex >= 0; rootIndex--) reheap(array, rootIndex, n-1); swap(array, 0, n-1); for (int lastIndex = n-2; lastIndex > 0; lastIndex--) { reheap(array, 0, lastIndex); swap(array, 0, lastIndex); } } private static void reheap(Comparable[] heap, int rootIndex, int lastIndex) { // Similar to statements from previous code. See next page…... } Efficiency is O(n log n). However, quicksort is usually a better choice. Efficiency is O(n log n). However, quicksort is usually a better choice.

29 private void reheap(reheap(Comparable[] heap, int rootIndex, int lastIndex) { boolean done = false; Comparable orphan = heap[rootIndex]; int largerChildIndex = 2 * rootIndex + 1; // index of left child, if any while (!done && (largerChildIndex <= lastIndex) ) { int rightChildIndex = largerChildIndex + 1; if ( (rightChildIndex <= lastIndex) && heap[rightChildIndex].compareTo(heap[largerChildIndex]) > 0) { largerChildIndex = rightChildIndex; } if (orphan.compareTo(heap[largerChildIndex]) < 0) { heap[rootIndex] = heap[largerChildIndex]; rootIndex = largerChildIndex; largerChildIndex = 2 * rootIndex + 1; // index of next left child } else done = true; } heap[rootIndex] = orphan; }