Crusher's Code
Time limit10sMemory limit128 MB
Compute the expected number of loop iterations for two randomized swap sorts on arrays of up to 8 values.
- Level
Hard8 of 10
- Topics
- Probability, Dynamic programming, Math
- Solved
- No attempts yet
Problem
Wesley Crusher is the teaching assistant for Introduction to Algorithms. In the first class the cadets were asked to come up with a sorting algorithm of their own. Monty came up with this code.
while (!sorted(a)) {
int i = random(n) ;
int j = random(n) ;
if (a[min(i,j)] > a[max(i,j)])
swap(a[i], a[j]) ;
}
Carlos, inspired by it, came up with this code.
while (!sorted(a)) {
int i = random(n-1) ;
int j = i + 1 ;
if (a[i] > a[j])
swap(a[i], a[j]) ;
}
The array a holds elements numbered 0 through , and the n in the code is that . Every call to random(k) independently picks one integer from 0 to , all with the same probability. The number of iterations is the number of times the body of the while statement runs. An iteration that only compares two values without swapping them still counts. An array that is already sorted never enters the body, so its number of iterations is 0.
Wesley has to decide which algorithm is better. Given an array of at most 8 values, compute the expected number of iterations each algorithm runs before that array is sorted.
Input
The first line contains the number of test cases ().
Each test case is given on a single line. The first value on the line is the number of array elements (), followed by the elements of the array separated by spaces. Every element is an integer from 0 to 100, and the same value may appear more than once.
Output
For each test case, print the expected number of iterations for Monty's algorithm and for Carlos's algorithm on one line, in the form Monty <Monty's expectation> Carlos <Carlos's expectation>.
Print both expectations with exactly six digits after the decimal point, rounding at the seventh digit. Put exactly one space between words, and no space at the start or the end of a line. No answer comes within of a rounding boundary, so the digits are the same whichever way a boundary would be resolved.