7 Quicksort Hsu LihHsing Computer Theory Lab 7
7. Quicksort Hsu, Lih-Hsing
Computer Theory Lab. 7. 1 Description of quicksort Chapter 7 n Divide n Conquer n Combine 2
Computer Theory Lab. Chapter 7 3
Computer Theory Lab. Partition(A, p, r) 1 2 3 4 5 6 7 8 Chapter 7 x A[r] i p– 1 for j p to r -1 do if A[j] ≤ x then i i + 1 exchange A[i] A[j] exchange A[i +1] A[r] return i +1 4
Computer Theory Lab. At the beginning of each iteration of the loop of lines 3 -6, for any array index k, 1. if p ≤ k ≤ i, then A[k] ≤ x. 2. if i + 1 ≤ k≤ j -1, then A[k] > x. 3. if k = r, then A[k] = x. Chapter 7 5
Computer Theory Lab. The operation of Partition on a sample array Chapter 7 6
Computer Theory Lab. Two cases for one iteration of procedure Partition Complexity: Partition on A[p…r] is (n) where n = r –p +1 Chapter 7 7
Computer Theory Lab. 7. 2 Performance of quicksort Chapter 7 8
Computer Theory Lab. Chapter 7 9
Computer Theory Lab. Intuition for the average case T(n) = (n logn) Chapter 7 10
Computer Theory Lab. 7. 3 Randomized versions of partition Chapter 7 11
Computer Theory Lab. 7. 4 Analysis of quicksort Chapter 7 12
Computer Theory Lab. 7. 4 -2 Chapter 7 13
Computer Theory Lab. 7. 4. 2 Expected running time n n Running time and comparsions Lemma 7. 1 n Chapter 7 Let X be the number of comparisons performed in line 4 of partition over the entire execution of Quicksort on an n-element array. Then the running rime of Quicksort is O(n+X) 14
Computer Theory Lab. we define {zi is compared to zj}, {zi is compared to zj} Chapter 7 15
Computer Theory Lab. Pr{zi is compared to zj} = Pr{zi or zj is first pivot chosen from Zij} = Pr{zi is first pivot chosen from Zij} + Pr{zj is first pivot chosen from Zij} Chapter 7 16
Computer Theory Lab. Chapter 7 17
Computer Theory Lab. another analysis Chapter 7 18
Computer Theory Lab. Chapter 7 19
Computer Theory Lab. Chapter 7 20
Computer Theory Lab. Chapter 7 21
- Slides: 21