東京大学 情報理工学系研究科 コンピュータ科学専攻 2019年2月実施 問題2
Author
Description
Consider the Java program below to sort an array
In this program, list
is a class of an integer list with the following methods:
lst.size()
: returns the number of elements in the listlst
.lst.get(i)
: returns the element at the-th position in the list lst
(the position number starts from 0).lst.insert(i, x)
: insertsto the list lst
at the-th position.
void mysort(int M, int N, int K, int[] A, list[] B) {
for (int i = 0; i < N; i++) {
int m = A[i] * K / M;
int j = 0;
for (; j < B[m].size(); j++) {
if (A[i] <= B[m].get(j)) {
break;
}
}
B[m].insert(j, A[i]);
}
int i = 0;
for (int m = 0; m < K; m++) {
for (int j = 0; j < B[m].size(); j++) {
A[i] = [ blank X ];
i = i + 1;
}
}
}
Answer the following questions:
(1) Answer an appropriate expression to fill the blank
(2) Let
(3) Explain how the expected running time of this program varies when
(4) Discuss advantages and disadvantages of this algorithm in comparison to the quicksort algorithm.
Kai
Setting of the problem: we got
(1)
B[m].get(j)
(2)
The input sequence might be in an increasing order and all elements might fall into one bucket.
Thus, line
times. Note that it has to be an increasing order, because items are being inserted at the beginning of a bucket. If we wanna do evil, we must make every item traverse the whole bucket, until the end. It is possible when every inserted item is bigger than any element in the bucket, that is, input sequence is of increasing order.
(3)
Let
Taking expectation:
What is
Since we have
We can also notice, that,
Finally:
The following contribute to total expected running time:
- finding a bucket for each element
- sorting each bucket,
- for each bucket, getting its content:
Total running time:
When
(4)
- BS is stable, QS isn't
- BS isn't in-place, QS is
- BS runs
expected, QS is - BS has upper limit on keys, QS hasn't