Properties of a heap (represented by an array A)

Similar documents
Heapsort. Heap data structure

Comparisons. Θ(n 2 ) Θ(n) Sorting Revisited. So far we talked about two algorithms to sort an array of numbers. What is the advantage of merge sort?

Comparisons. Heaps. Heaps. Heaps. Sorting Revisited. Heaps. So far we talked about two algorithms to sort an array of numbers

Heaps and Priority Queues

The Heap Data Structure

Heapsort. Algorithms.

Chapter 6 Heap and Its Application

Lecture 5: Sorting Part A

CS60020: Foundations of Algorithm Design and Machine Learning. Sourangshu Bhattacharya

Lecture: Analysis of Algorithms (CS )

A data structure and associated algorithms, NOT GARBAGE COLLECTION

Partha Sarathi Manal

BM267 - Introduction to Data Structures

CS 241 Analysis of Algorithms

Lecture 3. Recurrences / Heapsort

Heaps, Heapsort, Priority Queues

Introduction to Algorithms 3 rd edition

Overview of Presentation. Heapsort. Heap Properties. What is Heap? Building a Heap. Two Basic Procedure on Heap

Topic: Heaps and priority queues

Algorithms, Spring 2014, CSE, OSU Lecture 2: Sorting

Next. 1. Covered basics of a simple design technique (Divideand-conquer) 2. Next, more sorting algorithms.

1. Covered basics of a simple design technique (Divideand-conquer) 2. Next, more sorting algorithms.

CSE 3101: Introduction to the Design and Analysis of Algorithms. Office hours: Wed 4-6 pm (CSEB 3043), or by appointment.

9. Heap : Priority Queue

Priority Queues and Heaps. Heaps of fun, for everyone!

Collection of priority-job pairs; priorities are comparable.

Chapter 6 Heapsort 1

CS2223: Algorithms Sorting Algorithms, Heap Sort, Linear-time sort, Median and Order Statistics

Algorithms and Data Structures

Tirgul 4. Order statistics. Minimum & Maximum. Order Statistics. Heaps. minimum/maximum Selection. Overview Heapify Build-Heap

1 Interlude: Is keeping the data sorted worth it? 2 Tree Heap and Priority queue

Definition of a Heap. Heaps. Priority Queues. Example. Implementation using a heap. Heap ADT

Sorting and Searching

Data Structures and Algorithms Week 4

403: Algorithms and Data Structures. Heaps. Fall 2016 UAlbany Computer Science. Some slides borrowed by David Luebke

Basic Data Structures and Heaps

Sorting and Searching

Heap: A binary heap is a complete binary tree in which each, node other than root is smaller than its parent. Heap example: Fig 1. NPTEL IIT Guwahati

Data Structures and Algorithms Chapter 4

HEAP. Michael Tsai 2017/4/25

CSC Design and Analysis of Algorithms. Lecture 8. Transform and Conquer II Algorithm Design Technique. Transform and Conquer

Data Structures and Algorithms. Roberto Sebastiani

Data structures. Organize your data to support various queries using little time and/or space

CSC Design and Analysis of Algorithms. Lecture 8. Transform and Conquer II Algorithm Design Technique. Transform and Conquer

Algorithms Lab 3. (a) What is the minimum number of elements in the heap, as a function of h?

Heaps. Heapsort. [Reading: CLRS 6] Laura Toma, csci2000, Bowdoin College

EST Solutions. Ans 1(a): KMP Algorithm for Preprocessing: KMP Algorithm for Searching:

The priority is indicated by a number, the lower the number - the higher the priority.

CSE 241 Class 17. Jeremy Buhler. October 28, Ordered collections supported both, plus total ordering operations (pred and succ)

Adding a Node to (Min) Heap. Lecture16: Heap Sort. Priority Queue Sort. Delete a Node from (Min) Heap. Step 1: Add node at the end

Binary heaps (chapters ) Leftist heaps

Data Structures and Algorithms

Lower Bound on Comparison-based Sorting

CSCI2100B Data Structures Heaps

CSE5311 Design and Analysis of Algorithms. Administrivia Introduction Review of Basics IMPORTANT

Heaps Goodrich, Tamassia. Heaps 1

Priority Queues, Heaps, and Heapsort

CS S-08 Priority Queues Heaps 1

Thus, it is reasonable to compare binary search trees and binary heaps as is shown in Table 1.

Partha Sarathi Mandal

CS350: Data Structures Heaps and Priority Queues

Balanced Binary Search Trees. Victor Gao

Algorithms and Theory of Computation. Lecture 7: Priority Queue

How many leaves on the decision tree? There are n! leaves, because every permutation appears at least once.

Heapsort. Why study Heapsort?

Heaps. 2/13/2006 Heaps 1

HEAPS: IMPLEMENTING EFFICIENT PRIORITY QUEUES

CPSC 311 Lecture Notes. Sorting and Order Statistics (Chapters 6-9)

Heaps and Priority Queues

Sorted Arrays. Operation Access Search Selection Predecessor Successor Output (print) Insert Delete Extract-Min

CS 234. Module 8. November 15, CS 234 Module 8 ADT Priority Queue 1 / 22

Computer Science 210 Data Structures Siena College Fall Topic Notes: Priority Queues and Heaps

Heaps 2. Recall Priority Queue ADT. Heaps 3/19/14

Binary Heaps in Dynamic Arrays

Sorting. Popular algorithms: Many algorithms for sorting in parallel also exist.

Programming II (CS300)

CSE2331/5331. Topic 6: Binary Search Tree. Data structure Operations CSE 2331/5331

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs

Heaps. (our first advanced data structure)

Module 2: Priority Queues

CS 303 Design and Analysis of Algorithms

CS165: Priority Queues, Heaps

Trees & Tree-Based Data Structures. Part 4: Heaps. Definition. Example. Properties. Example Min-Heap. Definition

Priority Queues. Chapter 9

Sorting Shabsi Walfish NYU - Fundamental Algorithms Summer 2006

Data Structures Lesson 9

Data Structures and Algorithms

Arrays aren t going to work. What can we do? Use pointers Copy a large section of a heap, with a single pointer assignment

Questions from the material presented in this lecture

3. Priority Queues. ADT Stack : LIFO. ADT Queue : FIFO. ADT Priority Queue : pick the element with the lowest (or highest) priority.

Describe how to implement deque ADT using two stacks as the only instance variables. What are the running times of the methods

Appendix A and B are also worth reading.

How much space does this routine use in the worst case for a given n? public static void use_space(int n) { int b; int [] A;

Priority Queues. T. M. Murali. January 23, T. M. Murali January 23, 2008 Priority Queues

Priority Queues. T. M. Murali. January 29, 2009

CH 8. HEAPS AND PRIORITY QUEUES

Heap Model. specialized queue required heap (priority queue) provides at least

CSE 214 Computer Science II Heaps and Priority Queues

Figure 1: A complete binary tree.

Priority queues. Priority queues. Priority queue operations

Transcription:

Chapter 6. HeapSort

Sorting Problem Input: A sequence of n numbers < a1, a2,..., an > Output: A permutation (reordering) of the input sequence such that ' ' ' < a a a > 1 2... n

HeapSort O(n lg n) worst case like merge sort Sorts in place like insertion sort Only a constant number of array elements are stored outside the input array at any time Combines the best of both algorithms Design technique: use of a data structure: heap To understand HeapSort, study Heaps and Heap operations

Heap: Data Structure(1) (Binary) Heap is a nearly complete binary tree. The tree is completely filled on all levels except possibly the lowest, which is filled from the left up to a point Properties of a heap (represented by an array A) Length [A]: # of elements in A Heap-size [A]: # of elements in the heap stored within A Height of node = # of edges on a longest simple path from the node down to a leaf. Height of heap = height of root = Θ(lg n).

Heap: Data Structure(2) A heap can be stored as an array A[1.. n]. Root of tree is A[1]. Parent of A[i ] = A[ i / 2 ] Left child of A[i ] = A[2i ]. Right child of A[i ] = A[2i + 1]. Computing is fast with binary representation implementation.

Heap: Property For max-heaps (largest element at root), max-heap property: for all nodes i,, excluding the root, A[PARENT(i )] A[i]. For min-heaps (smallest element at root), min-heap property: for all nodes i,, excluding the root, A[PARENT(i )] A[i]. The maximum(or minimum) element of a max-heap(or min- heap) is at the root. The heap-sort algorithm uses max-heaps. Min-heap are commonly used in priority queues In general, heaps can be k-ary tree (instead of binary).

Maintaining the Heap property Always maintain the max-heap property: MAX-HEAPIFY Before MAX-HEAPIFY, A[i] may be smaller than its children. Assume left and right sub-trees of i are max-heaps. After MAX-HEAPIFY,, sub-tree rooted at i is a max-heap. The way MAX-HEAPIFY works: Compare A[i], A[LEFT(i)], and A[RIGHT(i)]. If necessary, swap A[i] with the larger of the two children to preserve heap property. Continue this process of comparing and swapping down the heap, until sub-tree rooted at i is max-heap. If we hit a leaf,, then the sub- tree rooted at the leaf is trivially a max-heap.

Sub-tree rooted at i

Time: O(h)=>O(lgn).

The children s subtree each have size at most 2n/3 T ( n) T (2 n / 3) + Θ(1) T ( n) = O(lg n)

Building a Heap Total time: O(n lg n)

Proof of Build-Heap

Bound analysis

Asymptotic Tight Bound

The HeapSort algorithm Given an input array, Builds a max-heap from the array. Starting with the root (the maximum element), the algorithm places the maximum element into the correct place in the array by swapping it with the element in the last position in the array. Discard this last node (knowing that it is in its correct place) by decreasing the heap size, and calling MAX-HEAPIFY on the new (possibly incorrectly-placed) root. Repeat this discarding process until only one node (the smallest element) remains, and therefore is in the correct place in the array.

Algorithm Sort in place Example:

1 10 9 2

Analysis: HEAPSORT(A, A, n) BUILD-MAX-HEAP( HEAP(A, A, n) : O(n) for i n down to 2 do : n-1 1 times exchange A[1] A[i] : O(1) MAX-HEAPFIY (A, 1,, i-1) : O(lg n) Total time: O(n lg n)

Priority Queue(1) A Priority Queue is a data structure for maintaining a dynamic set S of elements, each element has an associated value called a key. A priority queue is a data structure such that access or removal is of the highest-priority element in the collection, according to some method for comparing elements. Max-priority queue supports dynamic-set operations: INSERT(S, x): inserts element x into set S. MAXIMUM(S): returns element of S with largest key. EXTRACT-MAX(S): removes and returns element of S with largest key. INCREASE-KEY(S, x, k): increases value of element x s key to k.. Assume k x s current key value.

Priority Queue(2) Min-priority queue supports similar operations: INSERT(S, x): inserts element x into set S. MINIMUM(S): returns element of S with smallest key. EXTRACT-MIN(S): removes and returns element of S with smallest key. DECREASE-KEY(S, x, k): decreases value of element x s key to k.. Assume k x s current key value. Example of min-priority queue application: event-driven simulator. Example of max-priority queue application: job scheduling on a shared computer.

Heap implementation of Priority Queue Heaps efficiently implement priority queues. Max-heaps implemented with max-priority queues A Heap: a good compromise between fast insertion but slow extraction and vice versa. Both operations take O(lg n) time. Cf) A max-priority queues implemented by a Linked-List: insertion O(n) extraction O(1)

Finding the Maximum element: -- Get the root. MAXIMUM(S) Time: Θ(1)

Extracting Max element: EXTRACT-MAX(S) Given the array A: Make sure heap is not empty. Make a copy of the maximum element (the root). Make the last node in the tree the new root. Re-Heapify the heap, with one fewer node. Return the copy of the maximum element.

Analysis: Constant time assignment + Time for MAX-HEAPIFY Time: O(lg n).

Increasing Key Value: INCREASE-KEY(S, x, k) Given set S, element x, and new key value k: Make sure k x s current key. Update x s key value to k. Traverse the tree upward comparing x to its parent and swapping keys if necessary, until x s key is smaller than its parent s key.

Analysis: Upward path from node i has length O(lg n) in an n-element heap. Time: O(lg n)

Inserting into the Heap: INSERT(S, x) Given a key k to insert into the heap: Insert a new node in the very last position in the tree with key -. Increase the - key to k using the HEAP-INCREASE-KEY procedure defined above. Analysis: constant time assignments + time for HEAP-INCREASE-KEY. Time: O(lg n)

Homework 6.2-6, 6, 6.3-2,6.4-2,6.4-3 思考题 7-4 8