程序填空题:None-recursive QSelect algorithm
None-recursive QSelect algorithm
The function is to find the `K`-th smallest element in a list `A` of `N` elements. The initial function call is `QSelect(A, N, K)`. Please complete the following program.
```c++
ElementType QSelect( ElementType A[], int N, int K )
{
ElementType Pivot;
int L, R, Left, Right, K1;
Left = 0; Right = N-1; K1 = K;
for(;;) {
L = Left, R = Right+1;
Pivot = A[Left];
while (1) {
while ( A[++L] < Pivot ) ;
while ( A[--R] > Pivot );
if ( L < R ) Swap( &A[L], &A[R] );
else break;
}
@@[Swap( &A[Left], &A[R] )](3);
if ( K1 < (L-Left) )
@@[Right = R-1](3);
else if ( K1 > (L-Left) ){
K1 = K1-(L-Left);
Left = L;
}else
return Pivot;
}
}
```
答案:
第1空:Swap( &A[Left], &A[R] )
第2空:Right = R-1
The function is to find the `K`-th smallest element in a list `A` of `N` elements. The initial function call is `QSelect(A, N, K)`. Please complete the following program.
```c++
ElementType QSelect( ElementType A[], int N, int K )
{
ElementType Pivot;
int L, R, Left, Right, K1;
Left = 0; Right = N-1; K1 = K;
for(;;) {
L = Left, R = Right+1;
Pivot = A[Left];
while (1) {
while ( A[++L] < Pivot ) ;
while ( A[--R] > Pivot );
if ( L < R ) Swap( &A[L], &A[R] );
else break;
}
@@[Swap( &A[Left], &A[R] )](3);
if ( K1 < (L-Left) )
@@[Right = R-1](3);
else if ( K1 > (L-Left) ){
K1 = K1-(L-Left);
Left = L;
}else
return Pivot;
}
}
```
答案:
第1空:Swap( &A[Left], &A[R] )
第2空:Right = R-1