程序填空题:Heapsort
The function is to sort the array A in descending order. The function Swap(&A[0], &A[i]) is to exchange A[0] and A[i]. Please complete the following program.
c++
#define leftchild(i) (2*(i)+1)
void PercDown(ElementType A[], int i, int N) {
int child;
ElementType tmp;
for (tmp = A[i]; leftchild(i) < N; i = child) {
child = leftchild(i);
if ()
child++;
if (tmp > A[child])
A[i] = A[child];
else
break;
}
A[i] = tmp;
}
void Heapsort(ElementType A[], int N) {
int i;
for (i = N / 2; i >= 0; i--)
PercDown(A, i, N);
for (i = N - 1; i > 0; i--) {
Swap(&A[0], &A[i]);
;
}
}
答案:
第1空:child + 1 < N && A[child + 1] < A[child]
第2空:PercDown(A, 0, i)
c++
#define leftchild(i) (2*(i)+1)
void PercDown(ElementType A[], int i, int N) {
int child;
ElementType tmp;
for (tmp = A[i]; leftchild(i) < N; i = child) {
child = leftchild(i);
if ()
child++;
if (tmp > A[child])
A[i] = A[child];
else
break;
}
A[i] = tmp;
}
void Heapsort(ElementType A[], int N) {
int i;
for (i = N / 2; i >= 0; i--)
PercDown(A, i, N);
for (i = N - 1; i > 0; i--) {
Swap(&A[0], &A[i]);
;
}
}
答案:
第1空:child + 1 < N && A[child + 1] < A[child]
第2空:PercDown(A, 0, i)