exercise6-solved - Fundamental Computer Science I Solutions...

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

View Full Document Right Arrow Icon

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

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the 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,q-1) 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, i-1); (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, n-1) → quicksort (a, 1, n-2) → . .. → 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 (i-l < r-i) then (left interval smaller?) quicksort (a, l, i-1); l = i+1; | goto --> start of procedure | (instead of quicksort(a,i+1,r)) else quicksort (a, i+1, r); r = i-1; | goto --> start of procedure | (instead of quicksort(a,l,i-1)) 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.

Page1 / 5

exercise6-solved - Fundamental Computer Science I Solutions...

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

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