This preview shows pages 1–2. 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: CMPT 307 — Data Structures and Algorithms Outline Solutions to Exercises on Sorting 1. Show that the second smallest of n elements can be found with n + ceilingleft log n ceilingright - 2 comparisons in the worst case. The smallest of n numbers can be found with n- 1 comparisons as follows: Compare all the numbers in pairs. Only the smaller of each pair could possibly be the smallest of all n , so the problem has been reduced to that of finding the smallest of ceilingleft n/ 2 ceilingright numbers. Compare those numbers in pairs, and so on, until there is just one number left, which is the answer. To see that this algorithm does exactly n- 1 comparisons, notice that each number except the smallest loses exactly once. Or else you can conseder the decision tree that has n leaves, and so n- 1 internal nodes, as the tree is a full binary tree. In the search for the smallest number, the second smallest number must have come out smallest in every compar- ison made with it until it was eventually compared to the smallest. So the second smallest is among the elements that were compared with the smallest during the first phase. To find it, conduct another selection process (as above) to find the smallest of these numbers. At most ceilingleft log n ceilingright (the height of the tree of comparisons) elements were compared with the smallest, so finding the smallest of these takes ceilingleft log n ceilingright - 1 comparisons in the worst case. The total number of comparisons made is n- 1 + ceilingleft log n ceilingright - 1 = n + ceilingleft log n ceilingright - 2 in the worst case. 2. Suppose that you have a “black box” worst-case linear time median subrouting. Give a simple, linear time algorithm that solves the selection problem for an arbitrary order statistics. We assume that are given a procedure Median that takes as parameters an array A and subarray indices p and r , and returns the value of the median element of A [ p...r ] in O ( r- p ) in the worst case....
View Full Document