5
Design and Analysis of Algorithms HW6_solution Exercise 7.25 Exercise 7.32

Design and Analysis of Algorithms HW6 solution

  • Upload
    others

  • View
    25

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Design and Analysis of Algorithms HW6 solution

Design and Analysis of Algorithms   

HW6_solution 

Exercise 7.2‐5 

 

 

Exercise 7.3‐2 

 

Page 2: Design and Analysis of Algorithms HW6 solution

Exercise 7.4‐3 

 

 

Problem 7‐2* 

(a)  

Worst case :  Θ(n^2)  

(b)  

1. select a pivot s 

2. swap(a[s],a[r]) 

3. i=p‐1,j=r‐1 

4. for k=p ‐>r 

      if a[k]<x => i++;swap(a[i],a[k]); 

            if a[k]=x => j‐‐; swap(a[j],a[k]); 

      5. swap i~j‐1 to j~r 

      Return I,i+r‐j+1; 

 

(c)  

(1) 

RANDOMIZE‐PARTITION’(A,p,r) 

i = RANDOM(p,r); 

exchange A[r] with A[i] 

PARTITION’(A,p,r); 

 

 

Page 3: Design and Analysis of Algorithms HW6 solution

      (2) 

      QUICKSORT’(A,p,r) 

      { 

          If(p<r) 

        (q,t)=RANDOMIZE‐PARTITION’(A,p,r); 

        QUICKSORT’(A,p,q‐1); 

        QUICKSORT’(A,t+1,r) 

    } 

 

(d)  

Best : Θ(n) Average : Θ(nlgn) 

 

(Bonus) Problem 7‐3 

(a) 

 

 

(b) 

  

 

 

 

 

Page 4: Design and Analysis of Algorithms HW6 solution

(c) 

 

 

 

 

 

 

 

 

 

 

 

 

Page 5: Design and Analysis of Algorithms HW6 solution

(d) 

 

 

(e)