This preview shows pages 1–3. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: Fundamental Computer Science I Solutions to Assignment 6 Exercise 6.1 Let n be the number of keys sorted by the quicksort algorithm. 1. Show that quicksort needs at least Θ( n ) additional memory on the stack for saving return addresses. 2. * Show that a small modification of the function Quicksort(A,p,r) reduces the memory com plexity to O (log n ). Hint: Modify the algorithm using a suitable ordering of the calls Quicksort(A,p,q1) and Quicksort(A,q+1,r) . Solution 1. We first find the bound in the situation when the list is already sorted. Let’s observe again the Quicksort algorithm: quicksort (sequence a, integers l, r) begin ..... ..... (i = position of pivot element) quicksort (a, l, i1); (left recursive call) (1) quicksort (a, i+1, r); (right recursive call) (2) end Since the pivot element is always the last (hence the largest element), the following recursive calls take place at line (1): quicksort (a, 1, n1) → quicksort (a, 1, n2) → . .. → quicksort (a, 1, 1) where → indicates that the second function is called by the first. (Only then, in general, the program reaches line (2) for the first time.) It is clear that at least n 1 return addresses need to be saved on the stack at the same time, hence the Ω( n ) lower bound. Since at each recursive call, the interval length decreases by at least 1, the recursion depth cannot exceed O ( n ). Hence we need exactly Θ( n ) memory. squaresolid 2. We replace both recursive calls with the following lines: if (il < ri) then (left interval smaller?) quicksort (a, l, i1); l = i+1;  goto > start of procedure  (instead of quicksort(a,i+1,r)) else quicksort (a, i+1, r); r = i1;  goto > start of procedure  (instead of quicksort(a,l,i1)) It is obviously irrelevant, in the original procedure, whether we sort the left interval first and then the right, or the other way around....
View
Full
Document
This note was uploaded on 05/04/2010 for the course CS 320251 taught by Professor Nuechter during the Fall '09 term at Jacobs University Bremen.
 Fall '09
 Nuechter
 Algorithms, Data Structures, Sort

Click to edit the document details