algo_ch7_quick_sort

# 17 in place partitioning example a 6 2 8 5 11 10 4 1

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ively. 17 In-Place Partitioning Example A 6 2 8 5 11 10 4 1 9 7 3 A 6 2 3 5 11 10 4 1 9 7 8 A 6 2 3 5 1 10 4 11 9 7 8 A 6 2 3 5 1 4 10 11 9 7 8 10 A 4 2 3 5 1 4 10 11 9 7 8 6 18 Runtime of Quicksort Worst case: Worst every time nothing to move pivot = left (right) end of subarray Θ(n2) 0123456789 0 123456789 n 89 8 9 19 Worst Case Partitioning The running time of quicksort depends on whether The the partitioning is balanced or not. balanced Θ(n) time to partition an array of n elements Let T(n) be the time needed to sort n elements Let T(0) = T(1) = c, where c is a constant When n &gt; 1, When T(n) = T(|left|) + T(|right|) + Θ(n) T(n) is maximum (worst-case) when either |left| = 0 or |right| = 0 following each partitioning 20 Worst Case Partitioning 21 Worst Case Partitioning Worst-Case Performance (unbalanced): WorstPerformance T(n) = T(1) + T(n-1) + Θ(n) partitioning takes Θ(n) = 2 + 3 + 4 + …+ n-1 + n + n = = ∑k = 2 to nΘ(k) + n = Θ( ∑k = 2 to nk) + n = Θ(n2) This occurs when This the input is completely sorted or when or the pivot is always the smallest (largest) element 22 Worst-Case Analysis T(n) = max (T(q) + T(n - q - 1)) + Θ(n) 0 ≤ q ≤ n-1 where q ranges from 0 to n-1 since the procedure PARTITION produces two sub-problems with total size n-1 Substitution method: Guess T(n) ≤ cn2 T(n) ≤ max (cq2 + c(n - q - 1)2) + Θ(n) 0 ≤ q ≤ n-1 = c · max (q2 + (n - q - 1)2) + Θ(n) 0 ≤ q ≤ n-1 Take derivatives to get maximum at q = 0, n-1: T(n)...
View Full Document

Ask a homework question - tutors are online