Thursday 8 October 2015
2.1 More recursion
Problem 2.1 Consider the selection sort algorithm as described in the videos:
- For ,
- for ,
- if , then swap with
Rewrite the selection sort algorithm in recursive form.
Hint: Consider the array at the start of iteration In the outer loop. Can you identify a subarray which has to be sorted?
2.2 Recurrences
Exercise 2.1 Give recurrence equations to give the number of comparisons required to sort an -element array using insertion sort.
Exercise 2.2 Tabulate the following recurrence for :
Can you spot a pattern? Try to guess a closed form expression.
2.3 Split and Conquer
Exercise 2.3 How many multiplications are needed to calculate in the worst case, using square-and-multiply? Give a recurrence equation in terms of .
________________________________________________________________________________ ________________________________________________________________________________
- Algorithm SquareNmultiply
- if , return
- SquareNmultiply
- if ,
- else
- return
Exercise 2.4 Give recurrence equations to give the number of comparisons required to sort an -element array using merge sort.
Exercise 2.5 Consider a sorted array as input. Devise an algorithm which finds a given element in .
- Give an iterative formulation of your algorithm,
- Give a recursive formulation of your algorithm,
- How many comparisons does your algorithm require to find
?
Would it be possible to make it faster? Minimal solution: The algorithm iterates until the element is found or the search space is empty. The search space is halved each time so it takes itereations before it is empty. Assuming that is a power of 2, we need comparisons in the worst case.
This algorithm is faster than the linear search which takes comparisons to find a given element. No faster algorithm is known.
Additional comments for an advanced solution:
We could reduce the number of comparisons by a factor of two in the worst case, by skipping the equality check (Line 2d of the recursive definition, Line 1g of the iterative definition), and only check for equality at the end when the search space has size 1. This is unlikely to help the practical running time though.
To see that no significant speed improvements can be made, one can argue that if elements are random, and you have absolutely no idea where the desired element is, you can do nothing better than halving the search space with each comparison, and at least comparisons are required in the worst case before the search space is exhausted. It is useful to be able to see this idea intuitively. It can be formalised using information theory, but that is out of scope for this module.