(III)
The running time is O(N
3
).
(IV)
The running time is O(N
2
).
(V)
j can be as large as i
2
, which could be as large as N
2
. k can be as large as j, which is N
2
. The running time
is thus proportional to NN
2
N
2
, which is O(N
5
).
(VI)
The if statement is executed at most N
3
times, by previous arguments, but it is true only O(N
2
) times
(because it is true exactly i times for each i). Thus the innermost loop is only executed O(N
2
) times. Each
time through, it takes O(j
2
) = O(N
2
) time, for a total of O(N
4
). This is an example where multiplying loop
sizes can occasionally give an overestimate.
2.8
(a) It should be clear that all algorithms generate only legal permutations. The first two algorithms have tests
to guarantee no duplicates; the third algorithm works by shuffling an array that initially has no duplicates, so
none can occur. It is also clear that the first two algorithms are completely random, and that each permutation
is equally likely. The third algorithm, due to R. Floyd, is not as obvious; the correctness can be proved by
induction. See J. Bentley, “Programming Pearls,” Communications of the ACM 30 (1987), 754–757. Note
that if the second line of algorithm 3 is replaced with the statement
swap References( a[i], a[ ran dint( 0, n–1 ) ] );
then not all permutations are equally likely. To see this, notice that for N = 3, there are 27 equally likely ways
of performing the three swaps, depending on the three random integers. Since there are only 6 permutations,
and 6 does not evenly divide 27, each permutation cannot possibly be equally represented.
(b) For the first algorithm, the time to decide if a random number to be placed in a[i] has not been used
earlier is O(i). The expected number of random numbers that need to be tried is N/(N – i). This is obtained as
follows: i of the N numbers would be duplicates. Thus the probability of success is (N – i)/N. Thus the
expected number of independent trials is N/(N – i). The time bound is thus
N 1
Ni
N 1
N
2
N 1
2
2
N
1
2
i0
i0
N
N
i0
O(N
j 1
log N )
The second algorithm saves a factor of i for each random number, and thus reduces the time bound to
O(N log N) on average. The third algorithm is clearly linear.
(c,d) The running times should agree with the preceding analysis if the machine has enough memory. If not,
the third algorithm will not seem linear because of a drastic increase for large N.
评论0
最新资源