Sorting 9/15/2009. Sorting Problem. Insertion Sort: Soundness. Insertion Sort. Insertion Sort: Running Time. Insertion Sort: Soundness

Similar documents
Sorting in Linear Time. Data Structures and Algorithms Andrei Bulatov

Homework 1 Solutions MA 522 Fall 2017

Graphs. Minimum Spanning Trees. Slides by Rose Hoberman (CMU)

Heaps. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015

Data Structures and Algorithms Part 1.4

Algorithm Design Techniques. Divide and conquer Problem

Chapter 24. Sorting. Objectives. 1. To study and analyze time efficiency of various sorting algorithms

Lecture 5. Counting Sort / Radix Sort

why study sorting? Sorting is a classic subject in computer science. There are three reasons for studying sorting algorithms.

Data Structures Week #9. Sorting

CIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19

CSE 2320 Notes 8: Sorting. (Last updated 10/3/18 7:16 PM) Idea: Take an unsorted (sub)array and partition into two subarrays such that.

Priority Queues. Binary Heaps

CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13

QuickSort and Others. Data Structures and Algorithms Andrei Bulatov

CIS 121. Introduction to Trees

Major CSL Write your name and entry no on every sheet of the answer script. Time 2 Hrs Max Marks 70

6.854J / J Advanced Algorithms Fall 2008

DATA STRUCTURES. amortized analysis binomial heaps Fibonacci heaps union-find. Data structures. Appetizer. Appetizer

CIS 121 Data Structures and Algorithms with Java Fall Big-Oh Notation Tuesday, September 5 (Make-up Friday, September 8)

quality/quantity peak time/ratio

Lower Bounds for Sorting

Computational Geometry

Lecturers: Sanjam Garg and Prasad Raghavendra Feb 21, Midterm 1 Solutions

Chapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

The isoperimetric problem on the hypercube

COSC 1P03. Ch 7 Recursion. Introduction to Data Structures 8.1

CSE 417: Algorithms and Computational Complexity

BST Sequence of Operations

Recursion. Recursion. Mathematical induction: example. Recursion. The sum of the first n odd numbers is n 2 : Informal proof: Principle:

Hash Tables. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015.

How do we evaluate algorithms?

Examples and Applications of Binary Search

Fundamental Algorithms

Introduction. Resources

prerequisites: 6.046, 6.041/2, ability to do proofs Randomized algorithms: make random choices during run. Main benefits:

Lecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming

Algorithm. Counting Sort Analysis of Algorithms

condition w i B i S maximum u i

CS211 Fall 2003 Prelim 2 Solutions and Grading Guide

Order statistics. Order Statistics. Randomized divide-andconquer. Example. CS Spring 2006

Merge Sort. Alexandra Stefan

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures

Greedy Algorithms. Interval Scheduling. Greedy Algorithms. Interval scheduling. Greedy Algorithms. Interval Scheduling

Data Structures Week #5. Trees (Ağaçlar)

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

6.851: Advanced Data Structures Spring Lecture 17 April 24

2. ALGORITHM ANALYSIS

Minimum Spanning Trees

CSC165H1 Worksheet: Tutorial 8 Algorithm analysis (SOLUTIONS)

Minimum Spanning Trees. Application: Connecting a Network

Lecture 1: Introduction and Strassen s Algorithm

Divide and Conquer. Design and Analysis of Algorithms Andrei Bulatov

Lecture 6. Lecturer: Ronitt Rubinfeld Scribes: Chen Ziv, Eliav Buchnik, Ophir Arie, Jonathan Gradstein

Design and Analysis of Algorithms Notes

15-859E: Advanced Algorithms CMU, Spring 2015 Lecture #2: Randomized MST and MST Verification January 14, 2015

A Comparative Study on the Algorithms for a Generalized Josephus Problem

CS200: Hash Tables. Prichard Ch CS200 - Hash Tables 1

Massachusetts Institute of Technology Lecture : Theory of Parallel Systems Feb. 25, Lecture 6: List contraction, tree contraction, and

Pseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance

Algorithm Efficiency

Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

. Written in factored form it is easy to see that the roots are 2, 2, i,

EE123 Digital Signal Processing

of types having a total order and a predecessor and a successor function. In the

A graphical view of big-o notation. c*g(n) f(n) f(n) = O(g(n))

Minimum Spanning Trees

Combination Labelings Of Graphs

Chapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

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

We can use a max-heap to sort data.

Computer Science Foundation Exam. August 12, Computer Science. Section 1A. No Calculators! KEY. Solutions and Grading Criteria.

Python Programming: An Introduction to Computer Science

Chapter 3 Classification of FFT Processor Algorithms

Thompson s Group F (p + 1) is not Minimally Almost Convex

The Magma Database file formats

5.3 Recursive definitions and structural induction

n n B. How many subsets of C are there of cardinality n. We are selecting elements for such a

Appendix D. Controller Implementation

GC05: Algorithmic Complexity & Computability

Computers and Scientific Thinking

Priority Queues and Heaps (Ch 5.5) Huffman Coding Trees (Ch 5.6) Binary Search Trees (Ch 5.4) Lec 5: Binary Tree. Dr. Patrick Chan

Chapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Σ P(i) ( depth T (K i ) + 1),

top() Applications of Stacks

Chapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

EECS 2011M: Fundamentals of Data Structures

EE 459/500 HDL Based Digital Design with Programmable Logic. Lecture 13 Control and Sequencing: Hardwired and Microprogrammed Control

Graphs. Shortest Path and Topological Sort

Abstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:

Lecture 5: Sorting Part A

On Sorting an Intransitive Total Ordered Set Using Semi-Heap

UNIT 1 RECURRENCE RELATIONS

A Dynamic Separator Algorithm

Outline. CS 561, Lecture 6. Priority Queues. Applications of Priority Queue. For NASA, space is still a high priority, Dan Quayle

Pattern Recognition Systems Lab 1 Least Mean Squares

COMP250: Loop invariants

SECURITY PROOF FOR SHENGBAO WANG S IDENTITY-BASED ENCRYPTION SCHEME

A Generalized Set Theoretic Approach for Time and Space Complexity Analysis of Algorithms and Functions

The golden search method: Question 1

Transcription:

9/5/009 Algorithms Sortig 3- Sortig Sortig Problem The Sortig Problem Istace: A sequece of umbers Objective: A permutatio (reorderig) such that a ' K a' a, K,a a ', K, a' of the iput sequece The umbers are called keys Data Structures ad Algorithms Adrei Bulatov Algorithms Sortig 3-3 Algorithms Sortig 3-4 Isertio Sort The most atural sortig algorithm Iput: array A of legth Output: sorted array A for j= to do set key:=a[j] set i:=j- while i>0 ad A[i]>key do set A[i+]:= A[i], i:=i- set A[i+]:=key edwhile edfor Isert A[j] ito sorted sequece A[ j-] Isertio Sort: Soudess Isertio Sort cosists of a sigle loop We use techique called loop ivariat that is a property P such that (Iitializatio) it is true before the first iteratio of the loop (Maiteace) if it is true before a iteratio of the loop, it remais true before the ext iteratio (Termiatio) whe the loop termiates, the property helps to establish the correctess of the algorithm Ivariat for Isertio Sort: At the start of each iteratio of the for loop, the subarray A[ j ] cosists of the elemets origially i A[ j ] but i sorted order Algorithms Sortig 3-5 Algorithms Sortig 3-6 Isertio Sort: Soudess (Iitializatio) iitially j =, so the subarray of iterest cotais oly oe elemet, A[]. The ivariat is true (Maiteace) Suppose the property is true before iteratio j of the loop, i.e. the array A[ j ] is sorted. If A[i ] A[j] < A[i], the all the elemets A[i],, A[j ] are moved to the ext positio, ad A[j] is iserted i place of A[i], maitaiig the order (Termiatio) Obvious. Whe the loop termiates, all the A[ ] elemets are properly ordered. Isertio Sort: Ruig Time Iput: array A of legth Output: sorted array A for j= to do set key:=a[j] set i:=j- while i>0 ad A[i]>key do set A[i+]:= A[i], i:=i- set A[i+]:=key edwhile times j times edfor ( ) ( + 3( j )) = 3 j ( ) = 3 j= j= = O( )

9/5/009 Algorithms Sortig 3-7 Algorithms Sortig 3-8, Divide ad Coquer Recursive algorithms: Call themselves o subproblem Divide ad Coquer algorithms: Split a problem ito subproblems (divide) Solve subproblems recursively (coquer) Combie solutios to subproblems (combie) 5 4 7 3 6 5 4 7 3 6 Divide: Split a give sequece ito halves Coquer: By callig itself sort the two halves Combie: Merge the two sorted arrays ito oe 5 4 7 3 6 5 4 7 3 6 Algorithms Sortig 3-9 Algorithms Sortig 3-0 (A,p,r) Iput: array A, positios p,r Output: array A such that etries A[p],,A[r] are sorted if p<r the do set q:= (p+r)/ (A,p,q) (A,q+,r) Merge(A,p,q,r) Merge The Merge procedure is applied to array A ad three positios p, q, r i this array Assume p q < r A[p],, A[q] ad A[q+],, A[r] are ordered Outputs ordered sequece i positios A[p],, A[r] This sequece is geerated by comparig the two elemets o the top of subarrays ad movig the smaller oe Algorithms Sortig 3- Algorithms Sortig 3- Merge Merge: Soudess Merge(A,p,q,r) set u:=q-p+, set v:=r-q set L[...u]:=A[p...q] set R[...v]:=A[q+...r] set i:=, j:= for k=p to r do if l[i] R[j] the set A[k]:=L[i], i:=i+ else set A[k]:=R[j], j:=j+ edfor set L[u+]:= set R[v+]:= setiel cards Ivariat for Merge: At the start of each iteratio of the for loop, the subarray A[p k-] cotais the k p smallest elemets of L[ u+] ad R[ v+] i sorted order. Moreover, L[i] ad R[j] are the smallest elemets of the correspodig arrays that have ot bee copied to A (Iitializatio) Iitially k = p, so the subarray A[p k ] is empty. It cotais the k p = 0 smallest elemets of L ad R. Sice i = j =, both L[i] ad R[j] are the smallest elemets i the correspodig arrays. The ivariat is true

9/5/009 Algorithms Sortig 3-3 Algorithms Sortig 3-4 Merge: Soudess Example (Maiteace) Suppose the property is true before iteratio k of the loop. If L[i] R[j], the L[i} is the smallest elemet ot yet copied ito A. Sice A[p k ] cotais the k p smallest elemets, after the iteratio L[i] is copied ito A[k], ad A[p k] cotais the k p + smallest elemets. New top elemets of L ad R are clearly the smallest oes After icremetig k the loop ivariat is true agai If L[i] < R[j] the argumet is similar (Termiatio) Obvious. Whe the loop termiates, A[p r] cotais the k p smallest elemets from L ad R, that is all but the setiels. 5 4 7 3 6 Algorithms Sortig 3-5 Algorithms Sortig 3-6 : Soudess returs a sorted array : Ruig Time The ruig time of Merge whe applied to two arrays of total size is Θ() Follows from the soudess of Merge. Fiish the proof yourself QED The ruig time, T(), of is T() = C + T(/) + T(/) + D If = the T() = C divide recursio Merge Recursio tree Algorithms Sortig 3-7 Algorithms Sortig 3-8 : Soudess Recursio tree i There are odes o level i C + D Each ode requires i work Total work o each level: There are log levels (C+D) The ruig time of is Θ( log ) Heaps The mai setback of the IsertioSort is that to isert it eeds to sca a substatial part of the array. Ca it be sped up? Yes! Usig biary trees --- heaps keys 8 4 7 6 4 0 9 3 A heap is a early complete biary tree Recall trees etc.

9/5/009 Algorithms Sortig 3-9 Algorithms Sortig 3-0 Heap Property Let Paret(i) deote the paret of the vertex i Max-Heap Property: Key(Paret(i)) Key(i) for all i Mi-Heap Property: Key(Paret(i)) Key(i) for all i 6 Heaps Nearly complete biary tree meas that the legth of ay path from the root to a leaf ca vary by at most oe The height of a vertex i is the legth of the logest simple dowward path from i Therefore the height of the root is aroud log 4 0 8 7 9 3 4 Algorithms Sortig 3- Algorithms Sortig 3- Heap Operatios Creatig a max-heap Accessig the miimal elemet (root) Isertig a elemet Deletig a elemet Goal ruig time O() O() O(log ) O(log ) Implemetig Heaps ad Operatios Heap ca be implemeted by a array 6 4 0 8 7 9 3 4 Childre: leftchild(i) = i rightchild(i) = i + Paret: paret(i) = i / Legth: legth(h) = the umber of elemets i H Algorithms Sortig 3-3 Algorithms Sortig 3-4 Isertio Isert(H,key) set :=legth(), set H[+]:=key HeapifyUp(H,+) HeapifyUp(H,i) if i> the set j:=paret(i)= i/ if Key[H[i]]>Key[H[j]] the swap array etries H[i] ad H[j] HeapifyUp(H,j) HeapifyUp: Soudess The procedure HeapifyUp(H,i) fixes the heap property i O(log i) time, assumig that the array H is almost a heap with the key of H[i] too large. The ruig time of Isertio is O(log ) Iductio o i. Base Case i = is obvious Iductio Case: Swappig elemets takes O() time It remais to observe that after swappig H remais a heap or almost heap

9/5/009 Algorithms Sortig 3-5 Algorithms Sortig 3-6 Deletio Delete(H,i) set :=legth(), set H[i]:=H[] if Key[H[i]]>Key[H[paret(i)]] the HeapifyUp(H,i) if Key[H[i]]<Key[H[leftChild(i)]] or Key[H[i]]<Key[H[rightChild(i)]] the HeapifyDow(H,i) Deletio (ctd) HeapifyDow(H,i) set :=legth(h) if i> the Termiate with H uchaged else if i< the do set left:=i, right:=i+ let j be the idex that miimizes Key[H[left]] ad Key[H[right]] else if i= the set j:=i if Key[H[j]]>Key[H[i]] the swap array etries H[i] ad H[j] HeapifyDow(H,j) Algorithms Sortig 3-7 Algorithms Sortig 3-8 HeapifyDow: Soudess The procedure HeapifyDow(H,i) fixes the heap property i O(log i) time, assumig that the array H is almost a heap with the key of H[i] too small. The ruig time of Deletio is O(log ) Homework Explai how to implemet creatig a heap, accessig ad deletig the maximal elemet DIY