Chapter 8 Answers |
Document last modified: |
Question 8.3
Would the following produce the same results? Yes
Would the following produce the same decision tree, that is, the same number of comparisons? Yes
Diagram the left decision tree. Same as in notes.
Bubble sort
Question 8.4
- Guess (estimate) the worst and best case run time. O(n2)
- Is the sort ascending or descending? Ascending - the larger value is moved to higher index.
Comparisons
(n-1) + (n-2) + ... + 2 + 1 = n*(n-1) / 2
Question 8.5 - Worst case order? O(n2)
Sort on 3 elements A[1], A[2] and A[3]
Question 8.6
How many possible results (leaves) are there for sorting 3 elements? Count them. 6
What function of n=3 gives that result? 3*2*1=6. That is f(n) = n!
What would be the number of leaves for n=5? 120
What is P(n, n)? n!/(n-n)! = n!
What is a good guess for the height of the binary decision tree for sorting n elements? lg n!
Insertion sort
Question 8.7 - Which of the following analyses represent the best and the worst cases? Best then worst.
When does each occur? No insertion: c5 is O(n) and no c6 and c7 occur. When an insertion made, c5, c6 and c7 - are O(n2) operations.
T(n) = c1n + c2(n-1) + c4(n-1) + c5(n-1) + c8(n-1)
= (c1+ c2 + c4 + c5 + c8)n - (c2 + c4 + c5 + c8)
= an + b for some a and b constants
= an2 + bn + c for some constants a, b and c
Bounding sorts Ω(n lg n) and O(n lg n)
Question 8.8
What does Any binary comparison sort of n elements requires Ω(n lg n) comparisons in the worst case really mean? The fewest number of comparisons for an unsorted list.
Can we get lucky and do better? Only n comparisons to determine the list is sorted, but not to sort. worse? Remember the bubble sort, it was the same whether sorted or not, O(n2).