cs161-02 - Analyzing Insertion Sort as a Recursive...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
1 19 Analyzing Insertion Sort as a Recursive Algorithm Recursive Algorithm l Basic idea: divide and conquer » Divide into 2 (or more) subproblems. » Solve each subproblem recursively. » Combine the results. l Insertion sort is just a bad divide & conquer ! » Subproblems: (a) last element (b) all the rest » Combine: find where to put the last element Lecture 2, April 5, 2001 20 Recursion for Insertion Sort Recursion for Insertion Sort l We get a recursion for the running time T(n): l Formal proof: by induction. l Another way of looking: split into n subproblems, merge one by one. 1 2 ( 1 ) fo r 1 ( ) 1 fo r 1 ( ) ( 1) ( 2 ) ( ( 3 ) ( 2 ) ( ... ( ) n i T nn n T n n T n T n n T n n n T nn n n i n =  - + = = = - + = -+ - + = -+-+- + = =∑
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 21 Improving the insertion sort Improving the insertion sort l Simple insertion sort is good only for small n . l Balance sorting vs. merging: Merge equal size chunks. l How to merge: i=1, j=1 for k=1 to 2n if A(i)<B(j) then C(k)=A(i) i++ else C(k)=B(j) j++ end l O(n) time !! 22 Analysis Analysis l Iterative approach: » Merge size-1 chunks into size-2 chunks » Merge size-2 chunks into size-4 chunks » etc. l Intuitively right, but needs proof ! n merge n merge n merge n n 2 1 4 2 8 4 ( ) ( ) ( ) : ( log ) + + + L Overall Θ
Background image of page 2
3 23 Analyzing Recursive Merge Analyzing Recursive Merge -Sort Sort l Another approach: recursive. » Divide into 2 equal size parts. » Sort each part recursively. » Merge. l We directly get the following recurrence: l How to formally solve recurrence ? » For example, does it matter that we have Q (n) instead of an exact expression ?? » Does it matter that we sometimes have n not divisible by 2 ?? 2( / 2 ) ( ) 1 ( ) 1 1 T n n n T n n  + Θ = = •Recursion is a way of thinking.
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 10

cs161-02 - Analyzing Insertion Sort as a Recursive...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online