School of Computing Clemson University Fall, 2012

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)
Analysis of Algorithms
CS Section 600 CS Section 002 Dr. Angela Guercio Spring 2010.
Binary Heaps CSE 373 Data Structures Lecture 11. 2/5/03Binary Heaps - Lecture 112 Readings Reading ›Sections
1 COSC 2P03 Lecture #5 – Trees Part III, Heaps. 2 Today Take up the quiz Assignment Questions Red-Black Trees Binary Heaps Heap sort D-Heaps, Leftist.
0 Course Outline n Introduction and Algorithm Analysis (Ch. 2) n Hash Tables: dictionary data structure (Ch. 5) n Heaps: priority queue data structures.
PQ, binary heaps G.Kamberova, Algorithms Priority Queue ADT Binary Heaps Gerda Kamberova Department of Computer Science Hofstra University.
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.
ADT Table and Heap Ellen Walker CPSC 201 Data Structures Hiram College.
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.
Chapter 21 Priority Queue: Binary Heap Saurav Karmakar.
Analysis of Algorithms CS 477/677 Instructor: Monica Nicolescu Lecture 9.
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.
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.
CS 361 – Chapter 5 Priority Queue ADT Heap data structure –Properties –Internal representation –Insertion –Deletion.
S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 1 Adam Smith L ECTURES Priority Queues and Binary Heaps Algorithms.
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.
Mergeable Heaps David Kauchak cs302 Spring Admin Homework 7?
1 Chapter 6 Heapsort. 2 About this lecture Introduce Heap – Shape Property and Heap Property – Heap Operations Heapsort: Use Heap to Sort Fixing heap.
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.
1 Priority Queues (Heaps). 2 Priority Queues Many applications require that we process records with keys in order, but not necessarily in full sorted.
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)
Priority Queues A priority queue is an ADT where:
"Teachers open the door, but you must enter by yourself. "
CSE373: Data Structures & Algorithms Priority Queues
Andreas Klappenecker [partially based on the slides of Prof. Welch]
Heaps, Heapsort, and Priority Queues
Heaps, Heap Sort and Priority Queues
Priority Queues and Heaps
Lecture 15 AVL Trees Slides modified from © 2010 Goodrich, Tamassia & by Prof. Naveen Garg’s Lectures.
Hashing Exercises.
Source: Muangsin / Weiss
Heaps © 2010 Goodrich, Tamassia Heaps Heaps
Bohyung Han CSE, POSTECH
Heaps 9/13/2018 3:17 PM Heaps Heaps.
Heap Sort Example Qamar Abbas.
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
Chapter 2: Basic Data Structures
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}
CMSC 341: Data Structures Priority Queues – Binary Heaps
Part-D1 Priority Queues
Heapsort Heap & Priority Queue.
Ch 6: Heapsort Ming-Te Chi
Draw pictures to indicate the subproblems middleMax solves at each level and the resulting maxPtr and PrevPtr for each on this linked list:
i206: Lecture 14: Heaps, Graphs intro.
CMSC 341 Lecture 14 Priority Queues & Heaps
A Kind of Binary Tree Usually Stored in an Array
Heaps 11/27/ :05 PM Heaps Heaps.
Tree Representation Heap.
Ch. 8 Priority Queues And Heaps
"Teachers open the door, but you must enter by yourself. "
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) A heap.
Heapsort.
Binary and Binomial Heaps
HEAPS.
Binary SearchTrees [CLRS] – Chap 12.
Priority Queues Supports the following operations. Insert element x.
Hash Maps: The point of a hash map is to FIND DATA QUICKLY.
Data Structures and Algorithm Analysis Priority Queues (Heaps)
Computer Algorithms CISC4080 CIS, Fordham Univ.
Heaps & Multi-way Search Trees
Priority Queues Binary Heaps
Heaps 9/29/2019 5:43 PM Heaps Heaps.
CS210- Lecture 13 June 28, 2005 Agenda Heaps Complete Binary Tree
Presentation transcript:

School of Computing Clemson University Fall, 2012 Lecture 16. Binary Heaps CpSc 212: Algorithms and Data Structures Brian C. Dean School of Computing Clemson University Fall, 2012

Data Structure Review Abstract Data Types (Specifications) “Concrete” Implementations Sequences Stacks Queues Sets Maps Priority Queues “Databases” (i.e., multi-dimensional point sets) Arrays Linked Lists Hash Tables Binary Search Trees (many types of balancing mechanisms, B-trees, skip lists) Binary Heaps kd Trees, Suffix Trees, …

Priority Queues In a simple FIFO queue, elements exit in the same order as they enter. In a priority queue, the element with highest priority (usually defined as having lowest key) is always the first to exit. Many uses: Scheduling: Manage a set of tasks, where you always perform the highest-priority task next. Sorting: Insert n elements into a priority queue and they will emerge in sorted order. Complex Algorithms: For example, Dijkstra’s shortest path algorithm is built on top of a priority queue.

Priority Queues All priority queues support: Insert(e, k) : Insert a new element e with key k. Remove-Min : Remove and return the element with minimum key. In practice (mostly due to Dijsktra’s algorithm), many support: Decrease-Key(e, Δk) : Given a pointer to element e within the heap, reduce e’s key by Δk. Some priority queues also support: Increase-key(e, Δk) : Increase e’s key by Δk. Delete(e) : Remove e from the structure. Find-min : Return a pointer to the element with minimum key.

Redundancies Among Operations Given insert and delete, we can implement increase-key and decrease-key. Given decrease-key and remove-min, we can implement delete. Given find-min and delete, we can implement remove-min. Given insert and remove-min, we can implement find-min.

Priority Queue Implementations There are many simple ways to implement the abstract notion of a priority queue as a concrete data structure: insert remove-min Unsorted array or linked list O(1) O(n) Sorted array or linked list Binary heap O(log n) Balanced binary search tree

The Binary Heap An almost-complete binary tree (all levels full except the last, which is filled from the left side up to some point). Satisfies the heap property: for every element e, key(parent(e)) ≤ key(e). Minimum element always resides at root. Physically stored in an array A[0...n-1]. Easy to move around the array in a treelike fashion: Parent(i) = floor((i-1)/2). Left-child(i) = 2i + 1 Right-child(i) = 2i + 2. 2 5 3 9 8 6 5 1 2 3 4 5 6 7 8 9 A: 2 5 3 9 8 6 5 13 14 10 13 14 10 Actual array representation in memory Mental picture as a tree

Heap Operations : sift-up and sift-down All binary heap operations are built from the two fundamental operations sift-up and sift-down: sift-up(i) : Repeatedly swap element A[i] with its parent as long as A[i] violates the heap property with respect to its parent (i.e., as long as A[i] < A[parent(i)]). sift-down(i) : As long as A[i] violates the heap property with one of its children, swap A[i] with its smallest child. Both operations run in O(log n) time since the height of an n-element heap is O(log n). In some other places, sift-down is called heapify, and sift-up is known as up-heap.

Implementing Heap Operations Using sift-up and sift-down The remaining operations are now easy to implement in terms of sift-up and sift-down: insert : place new element in A[n+1], then sift-up(n+1). remove-min : swap A[n] and A[1], then sift-down(1). decrease-key(i, Δk) : decrease A[i] by Δk, then sift-up(i). increase-key(i, Δk) : increase A[i] by Δk, then sift-down(i). delete(i) : swap A[i] with A[n], then sift-up(i), sift-down(i). All of these clearly run in O(log n) time. General idea: modify the heap, then fix any violation of the heap property with one or two calls to sift-up or sift-down.

Caveat: You Can’t Easily Find Elements In Heaps (Except the Min) Actual Elements of Data: (say, stored in an array) Heap: e1 2 e2 e3 5 3 e4 e5 9 7 4 e6 e7 6 Each record in the data structure keeps a pointer to the physical element of data it represents, and each element of data maintains a pointer to its corresponding record in the data structure.

Building a Binary Heap We could build a binary heap in O(n log n) time using n successive calls to insert. Another way to build a heap: start with our n elements in arbitrary order in A[1..n], then call sift-down(i) for each i from n down to 1. Remarkable fact #1: this builds a valid heap! Remarkable fact #2: this runs in only O(n) time!

Bottom-Up Heap Construction The key property of sift-down is that it fixes an isolated violation of the heap property at the root: Using induction, it is now easy to prove that our “bottom-up” construction yields a valid heap. Possible heap property violations Valid Heap Valid Heap Valid Heap

Bottom-Up Heap Construction To analyze the running time of bottom-up construction, note that: At most n elements reside in the bottom level of the heap. Only 1 unit of work done to them by sift-down. At most n/2 elements reside in the 2nd lowest level, and at most 2 units of work are done to each of them. At most n/4 elements reside in the 3rd lowest level, and at most 3 units of work are done to them. So total time ≤ T = n + 2(n/2) + 3(n/4) + 4(n/8) + … (for simplicity, we carry the sum out to infinity, as this will certainly give us an upper bound). Claim: T = 4n = O(n)

“Shifting” Technique for Sums T = n + 2(n/2) + 3(n/4) + 4(n/8) + … - T/2 = n/2 + 2(n/4) + 3(n/8) + … T/2 = n + n/2 + n/4 + n/8 + … Applying the same trick again: T = 2n + n + (n/2) + (n/4) + … - T/2 = n + (n/2) + (n/4) + … T/2 = 2n

Heapsort Any priority queue can be used to sort. Just use n inserts followed by n remove-mins. The binary heap gives us a particularly nice way to sort in O(n log n) time, known as heapsort: Start with an array A[1..n] of elements to sort. Build a heap (bottom up) on A in O(n) time. Call remove-min n times. Afterwards, A will end up reverse-sorted (it would be forward-sorted if we had started with a “max” heap) Heapsort compares favorably to… Merge sort, because heapsort runs in place. Randomized quicksort, because heapsort is deterministic.

Treaps Heap BST 5 23 10 11 12 28 26 7 4 15 15 24 14 31 A treap is a binary tree in which each node contains two keys, a “heap key” and a “BST key”. It satisfies the heap property with respect to the heap keys, and the BST property with respect to the BST keys. The BST keys will store the elements of our BST; we’ll choose heap keys as necessary to assist in balancing.

Treaps If heap keys are all distinct, then there is only one valid “shape” for a treap. (why?) If we choose heap keys at random, then our treap will be randomly-structured! What about insert and delete? insert : Insert new element as leaf using the standard BST insertion procedure (so BST property satisfied). Assign new element a random heap key. Then restore heap property (while preserving BST property) using sift-up implemented with rotations. delete : Give element a heap key of +∞, sift it down (again using rotations, to preserve BST property) to a leaf, then delete it.

Mergeable Heaps : Motivation A mergeable (meldable) heap supports all fundamental priority queue operations as well as: merge(h1, h2) : merge heaps h1 and h2 into a single heap, destroying h1 and h2 in the process. The binary heap doesn’t seem to support merge any faster than in O(n) time. Why study mergeable heaps? They illustrate elegant data structure design techniques. Mergeable heaps are the first step along the road to more powerful priority queues, such as binomial heaps, pairing heaps, skew heaps, leftist heaps, and Fibonacci heaps.

Suppose we store our priority queue in a heap-ordered binary tree. Heap-Ordered Trees Suppose we store our priority queue in a heap-ordered binary tree. Not necessarily an “almost complete” tree though, so we can’t encode it succinctly in a single array as with the binary heap. Each node maintains a pointer to its parent, left child, and right child. The tree is not necessarily “balanced”. It could conceivably be nothing more than a single sorted path. 2 5 3 7 8 6 10

Suppose we can merge two heap-ordered trees in O(log n) time. All You Need is Merge… Suppose we can merge two heap-ordered trees in O(log n) time. All priority queue operations now easy to implement in O(log n) time! insert: merge with a new 1-element tree. remove-min: remove root, merge left & right subtrees. decrease-key(e): detach e’s subtree, decrease e’s key, then merge it back into the main tree. delete: use decrease-key + remove-min. increase-key: use delete + insert.

Recursively Merging Two Heap-Ordered Trees Take two heap-ordered trees h1 and h2, where h1 has the smaller root. Clearly, h1’s root must become the root of the merged tree. To complete the merge, recursively merge h2 into either the left or right subtree of h1: As a base case, the process ends when we merge a heap h1 with an empty heap, the result being just h1. h1: 2 h2: 5 L R Recursively merge into either L or R.