COMP 3170 Assignment 6
Helen Cameron
Due: Friday 29 June 2018 at 4:30 p.m.
Questions and Solutions
1. Consider the decision tree corresponding to insertion sort working on inputs of size 3 that we looked
at in class
...
COMP 3170 Assignment 6
Helen Cameron
Due: Friday 29 June 2018 at 4:30 p.m.
Questions and Solutions
1. Consider the decision tree corresponding to insertion sort working on inputs of size 3 that we looked
at in class. The basic operation vi < vj represents the comparison siftVal < nums[j].
(a) Which result (true or false) for that comparison represents the case when insertion sort is going
to move one position to the right (in the array) a value that is larger than siftValue?
Solution: True.
Explanation: (See Slide 20 in 04.2LowerBounds-SortingProof.pdf.) If the comparison shows
that siftVal < nums[j], then nums[j] has to be moved one position to the right in the array to
make room for a smaller siftVal. Thus, “true” is the result for that comparison that represents
the case when insertion sort is going to move one position to the right (in the array) a value that
is larger than siftValue.
(b) Consider all decision trees that correspond to the insertion sort code used in class working on
inputs of size 3, size 4, size 5, . . . . Using your answer to the previous question, which path in all
those decision trees corresponds to insertion sort doing the most moves to the right?
Solution: The path from the root to the leftmost leaf represents every basic operation (siftVal <
nums[j]) performed by insertion sort having the result true, making insertion sort move another
value to the right.
2. Consider the following comparison-based sorting algorithm called upDownSort:
1. void upDownSort( int[] nums ) {
2. int lo = 0, hi = nums.length-1;
3. while ( hi - lo > 0 ) { // at least 2 values remain to sort
4. swap( nums, hi, goingUp( nums, lo, hi ) );
5. hi--;
6. swap( nums, lo, goingDown( nums, lo, hi ) );
7. lo++;
8. } // end while
9. } // end sort
It uses the following method three methods: First, method goingUp, which returns an index:
1. int goingUp( int[] nums, int lo, int hi ) {
2. int resultIndex = lo;
3. for ( int i = lo+1; i <= hi; i++ )
4. if ( nums[ resultIndex ] <
[Show More]