以c语言编写:将已经存在的N个元素调整成最大堆或最小堆。 输入格式: 第一行是一个整数N,表示元素的个数,N<=10000。第二行N个元素的值。 输出格式: 输出2行,第一行是输入序列调整为最大堆后的元素序列,元素之间用空格分开。第二行是输入序列调整为最小堆后的元素序列,元素之间用空格分开。 输入样例: 在这里给出一组输入。例如: 8 7 5 8 4 2 3 6 1 输出样例: 在这里给出相应的输出。例如: 8 5 7 4 2 3 6 1 1 2 3 4 7 8 6 5
时间: 2024-03-20 12:43:25 浏览: 24
以下是构建最大堆和最小堆的C语言代码,实现将已有的N个元素调整成最大堆或最小堆,并输出调整后的序列:
```c
#include <stdio.h>
#define MAXN 10001 // 最大元素个数
// 调整成最大堆
void adjustToMaxHeap(int arr[], int n, int i) {
int parent = i, child = 2 * i + 1;
while (child < n) {
if (child + 1 < n && arr[child + 1] > arr[child]) {
child++;
}
if (arr[child] <= arr[parent]) {
break;
}
int temp = arr[child];
arr[child] = arr[parent];
arr[parent] = temp;
parent = child;
child = 2 * parent + 1;
}
}
// 调整成最小堆
void adjustToMinHeap(int arr[], int n, int i) {
int parent = i, child = 2 * i + 1;
while (child < n) {
if (child + 1 < n && arr[child + 1] < arr[child]) {
child++;
}
if (arr[child] >= arr[parent]) {
break;
}
int temp = arr[child];
arr[child] = arr[parent];
arr[parent] = temp;
parent = child;
child = 2 * parent + 1;
}
}
// 构建最大堆
void buildMaxHeap(int arr[], int n) {
for (int i = n / 2; i >= 0; i--) {
adjustToMaxHeap(arr, n, i);
}
}
// 构建最小堆
void buildMinHeap(int arr[], int n) {
for (int i = n / 2; i >= 0; i--) {
adjustToMinHeap(arr, n, i);
}
}
int main() {
int n;
scanf("%d", &n);
int arr[MAXN];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
buildMaxHeap(arr, n); // 调整成最大堆
for (int i = 0; i < n; i++) {
printf("%d", arr[i]);
if (i != n - 1) printf(" ");
}
printf("\n");
buildMinHeap(arr, n); // 调整成最小堆
for (int i = 0; i < n; i++) {
printf("%d", arr[i]);
if (i != n - 1) printf(" ");
}
printf("\n");
return 0;
}
```
输入样例:
```
8
7 5 8 4 2 3 6 1
```
输出样例:
```
8 5 7 4 2 3 6 1
1 2 3 4 7 8 6 5
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)