# CMPSCI 311: Theory of Algorithms

### David Mix Barrington

### Fall, 2003

### Discussion Notes #3

### from Wednesday 24 Sept 2003

### Applying the Master Theorem (Levitin Appendix B)

Here we will analyze some recursive algorithms and get recurrences
that we may solve using the Master Theorem. In each case explain and
ve your recurrence to get a Θ solution, that is, a function
f(n) that is Θ(T(n)) where T(n) is the actual worst-case
running time on inputs of length n.

Remember that because of the Smoothness Theorem we can ignore issues
caused by divide-and-conquer procedures not dividing the input into
equal pieces.

Please answer the questions *during the discussion period*.

**Question 1:**
The Stoogesort algorithm sorts an array of Comparables. Assume
for the discussion that it sorts correctly and analyze its running time.
```
void stoogesort (Comparable [] a, int i, int j)
{// sorts items i through j of array a
int size = j-i+1; // number of items to sort
int twothirds = 2*size/3;
if (size <= 3) {
trivialsort(a,i,j); // assume this is Theta(1)
return;}
stoogesort (a,i,i+twothirds-1);
stoogesort (a,j-twothirds+1,j);
stoogesort (a,i,i+twothirds-1);}
```

**Question 2:**
The Stoogesearch algorithm finds the target element in a sorted array
or returns -1 if it is not there. I've probably messed up the code,
but the idea is that it searches either the first 2/3 or last 2/3 of
the given range.

```
int stoogesearch (Comparable target, Comparable [] a,
int low, int high)
{// returns index of target if it is in a[low..high]
int size = high-low+1;
if (size == 1) if (a[low].equals(target)) return low;
else return -1;
else {int twothirds = 2*size/3;
if (a[high-twothirds].compareTo(target) < 0)
stoogesearch(target, a, high-twothirds+1, high);
else
stoogesearch(target, a, low, low+twothirds-1);}}
```

**Question 3:**
Here is a recursive algorithm for the closest pair problem,
given as pseudocode. Analyze its running time.

```
Given a set S of n points
If n <= 3 check all pairs and return closest, else
Divide S into two sets A and B of n/2 points each
Check each pair (a,b) with a in A and b in B
and find the closest
Find the closest pair within A recursively
Find the closest pair within B recursively
Return the closest of the three pairs you've found
```

Last modified 24 September 2003