Design and Analysis of Algorithms - Chapter 6 6

Similar documents
TECH. Problem: Sorting. Application of Sorting. Insertion Sort. Insertion Sort: Algorithm. Insertion Sort: Specification for subroutine

Lecture 7. Transform-and-Conquer

Heapsort. Algorithm : Design & Analysis [6]

CSC Design and Analysis of Algorithms

CSC Design and Analysis of Algorithms. Lecture 7. Transform and Conquer I Algorithm Design Technique. Transform and Conquer

2. Instance simplification Solve a problem s instance by transforming it into another simpler/easier instance of the same problem

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

CSC Design and Analysis of Algorithms. Lecture 7. Transform and Conquer I Algorithm Design Technique. Transform and Conquer

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

Transform & Conquer. Presorting

CPS 616 TRANSFORM-AND-CONQUER 7-1

CSC 421: Algorithm Design Analysis. Spring 2013

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

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

DATA STRUCTURES AND ALGORITHMS. Hierarchical data structures: AVL tree, Bayer tree, Heap

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

Algorithms and Data Structures

Algorithms in Systems Engineering ISE 172. Lecture 16. Dr. Ted Ralphs

CSC 1700 Analysis of Algorithms: Heaps

Data Structures and Algorithms

Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees

Sorting. Two types of sort internal - all done in memory external - secondary storage may be used

CSC 8301 Design and Analysis of Algorithms: Heaps

Heapsort. Heap data structure

Section 4 SOLUTION: AVL Trees & B-Trees

BM267 - Introduction to Data Structures

COS 226 Midterm Exam, Spring 2009

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

Module 4: Index Structures Lecture 13: Index structure. The Lecture Contains: Index structure. Binary search tree (BST) B-tree. B+-tree.

Lecture 5: Sorting Part A

Properties of a heap (represented by an array A)

9. Heap : Priority Queue

1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1

Module 2: Classical Algorithm Design Techniques

CS350: Data Structures Heaps and Priority Queues

CSCI2100B Data Structures Heaps

Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees

MergeSort. Algorithm : Design & Analysis [5]

Lecture 13: AVL Trees and Binary Heaps

Priority Queues. Lecture15: Heaps. Priority Queue ADT. Sequence based Priority Queue

ECE 242 Data Structures and Algorithms. Heaps I. Lecture 22. Prof. Eric Polizzi

Heaps and Priority Queues

Priority Queues and Binary Heaps

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

Lecture 6: Analysis of Algorithms (CS )

COSC160: Data Structures Heaps. Jeremy Bolton, PhD Assistant Teaching Professor

Sorting and Searching

Binary Heaps. COL 106 Shweta Agrawal and Amit Kumar

CISC 235: Topic 4. Balanced Binary Search Trees

Week 10. Sorting. 1 Binary heaps. 2 Heapification. 3 Building a heap 4 HEAP-SORT. 5 Priority queues 6 QUICK-SORT. 7 Analysing QUICK-SORT.

Recall: Properties of B-Trees

The Heap Data Structure

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

Priority Queues Heaps Heapsort

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

CMSC 341 Lecture 14: Priority Queues, Heaps

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

Sorting and Searching

Heaps Goodrich, Tamassia. Heaps 1

2-3 Tree. Outline B-TREE. catch(...){ printf( "Assignment::SolveProblem() AAAA!"); } ADD SLIDES ON DISJOINT SETS

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

Lecture 11: Multiway and (2,4) Trees. Courtesy to Goodrich, Tamassia and Olga Veksler

Week 10. Sorting. 1 Binary heaps. 2 Heapification. 3 Building a heap 4 HEAP-SORT. 5 Priority queues 6 QUICK-SORT. 7 Analysing QUICK-SORT.

Module 4: Dictionaries and Balanced Search Trees

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

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

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

Heaps. 2/13/2006 Heaps 1

Lecture: Analysis of Algorithms (CS )

Priority Queues. e.g. jobs sent to a printer, Operating system job scheduler in a multi-user environment. Simulation environments

CS Transform-and-Conquer

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

CS102 Binary Search Trees

Topic: Heaps and priority queues

Priority Queues (Heaps)

Design and Analysis of Algorithms Lecture- 9: Binary Search Trees

DATA STRUCTURES AND ALGORITHMS

Binary Heaps in Dynamic Arrays

Self-Balancing Search Trees. Chapter 11

CS 171: Introduction to Computer Science II. Binary Search Trees

Priority Queues Heaps Heapsort

Balanced Binary Search Trees. Victor Gao

CS 240 Fall Mike Lam, Professor. Priority Queues and Heaps

CS165: Priority Queues, Heaps

CMSC 341 Priority Queues & Heaps. Based on slides from previous iterations of this course

Binary search trees (chapters )

CS 240 Data Structures and Data Management. Module 2: Priority Queues

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

Module 2: Priority Queues

CS 240 Data Structures and Data Management. Module 2: Priority Queues

Data Structures Lesson 9

ADT Priority Queue. Heaps. A Heap Implementation of the ADT Priority Queue. Heapsort

Lecture: Analysis of Algorithms (CS )

Draw the resulting binary search tree. Be sure to show intermediate steps for partial credit (in case your final tree is incorrect).

Chapter 2: Basic Data Structures

Priority Queues, Heaps, and Heapsort

A data structure and associated algorithms, NOT GARBAGE COLLECTION

Trees. Eric McCreath

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

Data Structures and Algorithms

Transcription:

Transform & Conquer! Dr. Steve Goddard goddard@cse.unl.edu http://www.cse.unl.edu/~goddard/courses/csce310j Giving credit where credit is due: Most of the lecture notes are based on the slides from the Textbook s companion website http://www.aw.com/cssuport/ Some examples and slides are based on lecture notes created by Dr. Ben Choi, Louisiana Technical University and Dr. Chuck Cusack, UNL I have modified many of their slides and added new slides. Design and Analysis of Algorithms Chapter 6 1 Design and Analysis of Algorithms Chapter 6 2 Solve problem by transforming into: a more convenient instance of the same problem (instance implification) presorting Gaussian elimination a different representation of the same instance (representation change) balanced search trees heaps and heapsort polynomial evaluation by Horner s rule Fast Fourier Transform a different problem altogether (problem reduction) reductions to graph problems linear programming!" Solve instance of problem by transforming into another simpler/easier instance of the same problem Presorting: Many problems involving lists are easier when list is sorted. searching computing the median (selection problem) computing the mode finding repeated elements Design and Analysis of Algorithms Chapter 6 3 Design and Analysis of Algorithms Chapter 6 4 "# Find the k th smallest element in A[1], A[n]. Special cases: minimum: k = 1 maximum: k = n median: k = n/2 Presortingbased algorithm sort list return A[k] Partitionbased algorithm (Variable decrease & conquer): pivot/split at A[s] using partitioning algorithm from quicksort if s=k return A[s] else if s<k repeat with sublist A[s+1], A[n]. else if s>k repeat with sublist A[1], A[s1]. $"# Presortingbased algorithm: (nlgn) + (1) = (nlgn) Partitionbased algorithm (Variable decrease & conquer): worst case: T(n) =T(n1) + (n+1) > (n 2 ) best case: (n) average case: T(n) =T(n/2) + (n+1) > (n) Bonus: also identifies the k smallest elements (not just the k th ) Special cases max, min: better, simpler linear algorithm (brute force) Conclusion: Presorting does not help in this case. Design and Analysis of Algorithms Chapter 6 5 Design and Analysis of Algorithms Chapter 6 6 1

% Presortingbased algorithm: use mergesort (optimal): (nlgn) scan array to find repeated adjacent elements: (n) (nlgn) &' Elementary searching algorithms sequential search binary search binary tree search Brute force algorithm: (n 2 ) Conclusion: Presorting yields significant improvement Similar improvement for mode What about searching? Balanced tree searching AVL trees redblack trees multiway balanced trees (23 trees, 234 trees, B trees) Hashing separate chaining open addressing Design and Analysis of Algorithms Chapter 6 7 Design and Analysis of Algorithms Chapter 6 8 (! )!) *') The BST property still holds after a rotation. Left Rotation on (15, 25) Design and Analysis of Algorithms Chapter 6 9 Design and Analysis of Algorithms Chapter 6 10 * +( For every node, difference in height between left and right subtree is at most 1 * Algorithm maintains balance factor for each node. For example: AVL property is maintained through rotations, each time the tree becomes unbalanced lg n h 1.4404 lg (n + 2) 1.3277 average: 1.01 lg n + 0.1 for large n Disadvantage: needs extra storage for maintaining node balance A similar idea: redblack trees (height of subtrees is allowed to differ by up to a factor of 2) Design and Analysis of Algorithms Chapter 6 11 Design and Analysis of Algorithms Chapter 6 12 2

, )! #()! Design and Analysis of Algorithms Chapter 6 13 Design and Analysis of Algorithms Chapter 6 14 +( Small examples: 1, 2, 3 3, 2, 1 1, 3, 2 3, 1, 2 Definition: A heap is a binary tree with the following conditions: it is essentially complete: Larger example: 4, 5, 7, 2, 1, 3, 6 See figures 6.4, 6.5 for general cases of rotations; The key at each node is keys at its children Design and Analysis of Algorithms Chapter 6 15 Design and Analysis of Algorithms Chapter 6 16./0 Given n, there exists a unique binary tree with n nodes that is essentially complete, with h= lg n The root has the largest key The subtree rooted at any node of a heap is also a heap Design and Analysis of Algorithms Chapter 6 17 Design and Analysis of Algorithms Chapter 6 18 3

' If the elements to be sorted are arranged in a heap, we can build a sorted sequence in reverse order by repeatedly removing the element from the root, rearranging the remaining elements to reestablish the partial order tree property, and so on. How does it work? 1. Build heap 2. Remove root exchange with last (rightmost) leaf 3. Fix up heap (excluding last leaf) Repeat 2, 3 until heap contains just one node. Design and Analysis of Algorithms Chapter 6 19 Design and Analysis of Algorithms Chapter 6 20 Insert elements in the order given breadthfirst in a binary tree '.1/ base case is a tree consisting of one node Starting with the last (rightmost) parental node, fix the heap rooted at it, if it does not satisfy the heap condition: 1. exchange it with its largest child 2. fix the subtree rooted at it (now in the child s position) Example: 2 3 6 7 5 9 Design and Analysis of Algorithms Chapter 6 21 Design and Analysis of Algorithms Chapter 6 22 2 ) Input: A heap structure H that does not necessarily have the partial order tree property Output: H with the same nodes rearranged to satisfy the partial order tree property void constructheap(h) // Outline if (H is not a leaf) constructheap (left subtree of H); constructheap (right subtree of H); Element K = root(h); fixheap(h, K); return; T(n) = T(nr1) + T(r) + 2 lg(n) for n > 1 where r is the number of nodes in the right subheap T(n) θ(n); heap is constructed in linear time. The root of a heap can be deleted and the heap fixed up as follows: exchange the root with the last leaf compare the new root (formerly the leaf) with each of its children and, if one of them is larger than the root, exchange it with the larger of the two. continue the comparison/exchange with the children of the new root until it reaches a level of the tree where it is larger than both its children Design and Analysis of Algorithms Chapter 6 23 Design and Analysis of Algorithms Chapter 6 24 4

2 heapsort(e, n) // Outline construct H from E, the set of n elements to be sorted for (i = n; i >= 1; i) curmax = getmax(h) deletemax(h); E[i] = curmax; detelemax(h) // Outline copy the rightmost element of the lowest level of H into K delete the rightmost element on the lowest level of H fixheap(h, K); // reinsert K into a heap H with a vacant root assumed Actually, figures be show deltemax() in action Design and Analysis of Algorithms Chapter 6 25 Design and Analysis of Algorithms Chapter 6 26 %& 2 ) fixheap(h, K) // Outline if (H is a leaf) insert K in root(h); else set largersubheap to leftsubtree(h) or rightsubtree(h), whichever has larger key at is root. This involves one key comparison. if (K.key root(largersubheap.key) insert K in root(h); else insert root(largersubheap) in root(h); fixheap(largersubheap, K); return; FixHeap requires 2h comparisons of keys in the worst case on a heap with height h. T(n) 2 lg(n) Design and Analysis of Algorithms Chapter 6 27 Use an array to store breadthfirst traversal of heap tree: Example: 1 9 5 3 4 2 Left child of node j is at 2j Right child of node j is at 2j+1 Parent of node j is at j/2 1 2 3 4 5 6 9 5 3 1 4 2 Parental nodes are represented in the first n/2 locations Design and Analysis of Algorithms Chapter 6 28 *! ' See algorithm HeapBottomUp in section 6.4 Fix heap with problem at height j: 2j comparisons For subtree rooted at level i it does 2(hi) comparisons Total for heap construction phase: h1 2(hi) 2 i = 2 ( n lg (n + 1)) = (n) i=0 # nodes at level i Design and Analysis of Algorithms Chapter 6 29 Design and Analysis of Algorithms Chapter 6 30 5

'./ Recall algorithm: (n) 1. Build heap 2. Remove root exchange with last (rightmost) leaf (log n) 3. Fix up heap (excluding last leaf) Repeat 2, 3 until heap contains just one node. "' A priority queue is the ADT of an ordered set with the operations: find element with highest priority delete element with highest priority insert element with assigned priority Heaps are very good for implementing priority queues n 1 times Total: (n) + ( n log n) = (n log n) Note: this is the worst case. Average case also (n log n). Design and Analysis of Algorithms Chapter 6 31 Design and Analysis of Algorithms Chapter 6 32 3 Insert element at last position in heap. Compare with its parent and if it violates heap condition exchange them Continue comparing the new element with nodes up the tree until the heap condition is satisfied Example: *! 14!3 Top down: Heaps can be constructed by successively inserting elements into an (initially) empty heap Bottomup: Put everything in and then fix it Which one is better? Efficiency: Design and Analysis of Algorithms Chapter 6 33 Design and Analysis of Algorithms Chapter 6 34 6