Stooge sort.
The three stooges have come up with a sorting method that works like
this: Begin by sorting the bottom two thirds of the array,
then sort the top two thirds, and finish by sorting the first two thirds
again. Of course you use stooge sort recursively for the three sortings!
More precisely, here is the code for it.
template
void stoogeSort(Ptr b, Ptr e)
{ int n = e - b; // length of array.
if ( n == 2 ) // base case
{
if (b[1] <= b[0] ) swap(b[0],b[1]);
}
else if ( n > 2 ) // general case
{
int two_thirds = (2*n + 2)/3; // = ceiling((2/3)n).
stoogeSort(b, b+two_thirds); // Moe - bottom 2/3
stoogeSort(e-two_thirds, e); // Larry - top 2/3
stoogeSort(b, b+two_thirds); // Curly - bottom 2/3
}
}
- Explain how stoogeSort works (i.e. informally prove that it is correct).
Hint: what can you say about the data in the last one third of the array
after the second sort (Larry's)?
- Write a recurrence relation for T(n) = the number of data comparisons used
by stooge sort. Note that the only comparision in the code is the
"b[1] <= b[0]" when n is 2. In the recurrence relation you can use
(2/3)n as the size of the array regions sorted in the recursive calls,
even though the exact size is rounded up from that value.
For example, when n is 4, two_thirds would be 3 and the recursive calls
would be on arrays of that size. In the recurrence
formula we can approximate two_thirds by 2.666666667. This simplifies
the formula a lot. Doing this, we are actually computing a lower bound for
the true T(n) function.
- Using the master theorem (pg 268), obtain a "big O" expression for T(n).
How good a performer is stoogeSort?