東京大学 工学系研究科 電気系工学専攻 2024年8月実施 問題4 情報工学II
Author
Description
I.
TODO
II.
Consider the following algorithm
- for
or , do nothing. - for
, do nothing if , and overwrite as , otherwise. - for
, select an element of by using a function as . Let be an array consisting of all the elements in being smaller than , and be an array consisting of all the elements in being greater than . Overwrite as . Then, recursively apply to the subarrays and in as and , respectively.
Answer the following questions.
(1) Fig. 8 exemplifies the operation of
(2) Suppose that an array
(3) Assume that
(4) Program 1 is an implementation of the algorithm
(5) Suppose that
Fig. 8
(6,9,3,5,1,7)
|
(3,5,1) -- 6 - (9,7)
| | |
(1) - 3 - (5) | (7,9)
|____|____| | |
| | |
(1,3,5) -- 6 - (7,9)
|
(1,3,5,6,7,9)
/* Program1 */
void swap(int X[], int i, int j){
int tmp = X[i]; X[i] = X[j]; X[j] = tmp;
}
int partition (int X[], int left, int right) {
int pivot = X[left];
int i = right;
for (int j = right; j >= left+1; j--) {
if (X[j] >= pivot) {
[A]
i--;
}
}
[B]
return i;
}
void f(int X[], int left, int right) {
if (left < right) {
int pivotpos = partition(X, left, right);
[C]
}
}
int main (void) {
int X[10] = {9, 6, 1, 7, 2, 3, 4, 5, 0, 8};
f(X, 0, sizeof(X) / sizeof(X[0]) - 1);
return 0;
}
Kai
I.
TODO
II.
(1)
(6,8,4,5,2,3,1,9,7)
|
(4,5,2,3,1) -- 6 -- (8,9,7)
| | |
(2,3,1) --- 4 - (5) | (7) - 8 - (9)
| | | | |____|____|
(1) - 2 - (3) | | | |
|____|____| | | | (7,8,9)
| | | | |
(1,2,3) | | | |
|_______|____| | |
| | |
(1,2,3,4,5) | |
|_______|_______|
|
(1,2,3,4,5,6,7,8,9)
(2)
The worst case is when the partition is as unbalanced as possible.
Since we want the digits at the start of the array to be as large as possible.
In addition, each integer from 1 to 9 is one each.
Therefore, the worst case is 987654321, i.e.
For
(1,2,3,4,5,6,7,8,9)
_______|_________
| | |
(1,2,3,4) 5 (6,7,8,9)
_____|____ | _____|____
| | | | | | |
(1,2) - 3 - (4) | (6,7) - 8 - (9)
| | |
(3,4,2,1) - 5 --- (8,9,7,6)
|
(5,8,9,7,6,3,4,2,1)
Therefore, the best and largest case is 589763421.
(Note to readers: The C code provided in the question is unstable; it will swap the Pivot to the middle and swap the elements that were originally at the end to the beginning)
(3)
In the worst case, the time complexity
Since
i.e.
(4)
- A:
swap(X, i, j); - B:
swap(X, left, i); - C:
f(X, left, pivotpos-1); f(X, pivotpos+1, right)
(5)
Complexity:
Reason:
On average, the randomly chosen pivots splits the array into two subarrays of roughly proportional sizes.
Because balanced or near-balanced splits occur with constant probability, the expected height of the recursion tree becomes logarithmic, i.e.
The expected running time