```c void HeapAdjust(int H[], int start, int end) { // 将start到end之间的元素调整为最大堆 int temp = H[start]; int parent = start, child; while (2 * parent <= end) { child = 2 * parent; if (child != end && H[child] ++child; if (temp > H[child]) break; else { H[parent] = H[child]; parent = child; } } H[parent] = temp; }
void HeapSort(int H[], int L, int R) { // 调整整个二叉树为最大堆 for (int i = (R - L + 1) / 2; i >= L; --i) HeapAdjust(H, i, R); // 逐步将堆顶元素移至堆底 for (int i = R; i >= L; --i) { swap(&H[L], &H[i]); HeapAdjust(H, L, i - 1); } } ```
#### 测试样例 以下是一个完整的测试样例,展示了如何使用上述函数进行堆排序。
```c #include
void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; }
void HeapAdjust(int H[], int start, int end) { int temp = H[start]; int parent = start, child; while (2 * parent <= end) { child = 2 * parent; if (child != end && H[child] ++child; if (temp > H[child]) break; else { H[parent] = H[child]; parent = child; } } H[parent] = temp; }
void HeapSort(int H[], int L, int R) { for (int i = (R - L + 1) / 2; i >= L; --i) HeapAdjust(H, i, R); for (int i = R; i >= L; --i) { swap(&H[L], &H[i]); HeapAdjust(H, L, i - 1); } }
int main() { int A[] = {0, 1, 3, 63, 5, 78, 9, 12, 52, 8}; printf("Previous Array: "); for (int i = 1; i <= 9; ++i) printf("%d ", A[i]); HeapSort(A, 1, 9); printf("\nSorted Array: "); for (int i = 1; i <= 9; ++i) printf("%d ", A[i]); printf("\n"); return 0; } ```