编写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-26 20:38:09 浏览: 45
以下是实现题目要求的C语言程序:
```c
#include <stdio.h>
void AdjustUp(int arr[], int k); // 最小堆调整
void AdjustDown(int arr[], int k, int len); // 最大堆调整
void BuildMinHeap(int arr[], int len); // 建立最小堆
void BuildMaxHeap(int arr[], int len); // 建立最大堆
void PrintHeap(int arr[], int len); // 输出堆
int main() {
int n;
scanf("%d", &n);
int arr1[n+1], arr2[n+1];
for(int i = 1; i <= n; i++) {
scanf("%d", &arr1[i]);
arr2[i] = arr1[i];
}
BuildMaxHeap(arr1, n); // 建立最大堆
BuildMinHeap(arr2, n); // 建立最小堆
PrintHeap(arr1, n); // 输出最大堆
PrintHeap(arr2, n); // 输出最小堆
return 0;
}
void AdjustUp(int arr[], int k) {
while(k > 1 && arr[k] < arr[k/2]) {
int tmp = arr[k];
arr[k] = arr[k/2];
arr[k/2] = tmp;
k = k/2;
}
}
void AdjustDown(int arr[], int k, int len) {
int tmp = arr[k];
for(int i = 2*k; i <= len; i = 2*k) {
if(i < len && arr[i] < arr[i+1]) {
i = i+1;
}
if(tmp >= arr[i]) {
break;
} else {
arr[k] = arr[i];
k = i;
}
}
arr[k] = tmp;
}
void BuildMinHeap(int arr[], int len) {
for(int i = len/2; i >= 1; i--) {
AdjustUp(arr, i);
}
}
void BuildMaxHeap(int arr[], int len) {
for(int i = len/2; i >= 1; i--) {
AdjustDown(arr, i, len);
}
}
void PrintHeap(int arr[], int len) {
for(int i = 1; i <= len; i++) {
printf("%d", arr[i]);
if(i != len) {
printf(" ");
}
}
printf("\n");
}
```
阅读全文
相关推荐
![ppt](https://img-home.csdnimg.cn/images/20241231044937.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)