求堆排序的C语言代码和伪代码
时间: 2023-06-08 12:03:59 浏览: 106
以下是堆排序的C语言代码和伪代码:
C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define ArraySize 10 // 数组大小
void adjustHeap(int arr[], int i, int n) {
int temp = arr[i];
int j = 2 * i + 1;
while (j < n) {
if (j + 1 < n && arr[j] < arr[j + 1]) {
j++;
}
if (arr[j] > temp) {
arr[i] = arr[j];
i = j;
j = 2 * i + 1;
} else {
break;
}
}
arr[i] = temp;
}
void heapSort(int arr[], int n) {
for (int i = n / 2 - 1; i >= 0; i--) {
adjustHeap(arr, i, n);
}
for (int i = n - 1; i >= 1; i--) {
int temp = arr[i];
arr[i] = arr[0];
arr[0] = temp;
adjustHeap(arr, 0, i);
}
}
int main() {
int arr[ArraySize] = {6, 8, 5, 9, 2, 7, 1, 4, 3, 0};
heapSort(arr, ArraySize);
printf("排序后的数组:");
for (int i = 0; i < ArraySize; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
伪代码:
```
void adjustHeap(int arr[], int i, int n) {
int temp = arr[i];
int j = 2 * i + 1;
while (j < n) {
if (j + 1 < n && arr[j] < arr[j + 1]) {
j++;
}
if (arr[j] > temp) {
arr[i] = arr[j];
i = j;
j = 2 * i + 1;
} else {
break;
}
}
arr[i] = temp;
}
void heapSort(int arr[], int n) {
for (int i = n / 2 - 1; i >= 0; i--) {
adjustHeap(arr, i, n);
}
for (int i = n - 1; i >= 1; i--) {
int temp = arr[i];
arr[i] = arr[0];
arr[0] = temp;
adjustHeap(arr, 0, i);
}
}
```
其中,`adjustHeap`函数是堆排序中的调整堆的操作,`heapSort`函数是堆排序的入口函数。
阅读全文