hw03solutions

hw03solutions - CSE 331 Spring 2008 Homework 3 Solutions 1...

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

CSE 331 Spring 2008 Homework 3 Solutions 1. The following diagram shows how quicksort would operate on this list. All lists are given after the partitioning step. Pivots are shown in boldface . Only the sublist that quicksort actually works on is shown for each call. In this diagram, it assumed that quicksort works as given in the text, only modified so as not to call insertion sort. median3() swaps elements to find the pivot. For the following diagram, median3() swaps the pivot to the far right of the list. No other swapping is done during the partitioning step. This is different from the algorithm in the text. quicksort(A, 0, 0) 233, 132, 327, 414 , 877, 542, 433, 986, 554 132, 233 , 327 132 327 433, 542, 554 , 986, 877 433 , 542 542 877, 986 877 quicksort(A, 0, 2) quicksort(A, 2, 2) quicksort(A, 4, 5) quicksort(A, 4, 8) quicksort(A, 7, 8) quicksort(A, 5, 5) quicksort(A, 7, 7) 233, 132, 327, 414 , 986, 542, 433, 554, 877 132, 233 , 327 132 327 433, 542, 554, 877 , 986 433, 542 , 554 554 986 quicksort(A, 0, 2) quicksort(A, 2, 2) quicksort(A, 4, 6) quicksort(A, 4, 8) quicksort(A, 8, 8) quicksort(A, 4, 4) 433 quicksort(A, 6, 6) quicksort(A, 0, 0)

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

View Full Document
2. (a) We are given a sorted list of N integers, with O (1) randomly-ordered elements appended to the back. There are a couple different approaches we could take to sort this list in O (N) worst- case time. Probably the most obvious approach would be to just run insertion sort. Since the first N integers are already sorted, insertion sort would skip over them in O (N) time. After that, it would insert all of the randomly-generated elements into their appropriate places in the list. This will take O (N) time per element, since the sort may have to search through most of the list to find the correct place. Fortunately, since there are only O (1) elements that are out of order, it will take O (N) * O (1) = O (N) time to sort the whole list in the worst case. Note that you could use a binary search to find the correct place for each element in O (log N) time. This would be faster than the O (N) sequential search used by insertion sort. However, even if you did this, you would still have to make O (N) swaps to insert each element into its correct place in the array, so the complexity of the algorithm would not be any better. (b)
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 5

hw03solutions - CSE 331 Spring 2008 Homework 3 Solutions 1...

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

View Full Document
Ask a homework question - tutors are online