c - 堆排序打印出 0 而不是假定的数组元素
问题描述
当我遇到一些错误时,我正在尝试使用堆排序以升序打印输入数组序列号。
我的代码:
#include <stdio.h>
#include <conio.h>
void swap( float a[],int i, int j){
float temp = a[i];
a[i]=a[j];
a[j]=temp;
}
void PushDown (float a[],int first, int last){
int r = first;
while (r<=last/2)
if (last==2*r){
if (a[r]>a[last]) swap(a,r, last);
r=last;//break
}
else
if ((a[r]>a[2*r]) && (a[2*r]<=a[2*r+1])){
swap(a,r,2*r);
r=2*r;
}
else
if ((a[r]>a[2*r+1]) && (a[2*r+1]<=a[2*r])){
swap(a,r,2*r+1);
r=2*r+1;
}
else r=last; //break;
}
void HeapSort(float a[],int n){
int i;
for(i = (n-2)/2; i>=0; i--)
PushDown(a,i,n-1);
for(i = n-1; i>=2; i--) {
swap(a,a[0],a[i]);
PushDown(a,0,i-1);
}
swap(a,a[0],a[1]);
}
//NHAP DAY SO
void Nhapdayso(float a[],int n){
for(int i=0;i<n;i++){
printf("Nhap so thu %d: ",i+1);
scanf("%f",&a[i]);
}
}
//IN DAY SO
void Inday(float a[],int n){
for(int i=0;i<n;i++){
printf("%.f ",a[i]);
}
}
//CHUONG TRINH CHINH
int main(){
int n;
float a[50];
printf("Nhap so phan tu cua day so: ");
scanf("%d",&n);
Nhapdayso(a,n);
Inday(a,n);
HeapSort(a,n);
printf("\nDay so sau khi sap xep : ");
Inday(a,n);
getch();
return 0;
}
错误是:
示例:
测试用例:1 9 5 3
预期输出:1 3 5 9
实际输出:1 0 5 9
测试用例:12 99 50
预期输出:12 50 99
实际输出:12 99 50
测试用例:78 46 2
预期输出:2 46 78
实际输出:2 46 0
我怀疑我的 PushDown 函数有问题,但我就是想不通。
您的帮助将不胜感激。
解决方案
推荐阅读
- html - SVG 渲染问题 - Firefox 切断了兄弟 SVG 元素 - 有解决方法吗?
- linux-kernel - .config 文件存储在哪里为设备制作目标 linux 映像
- flutter - Flutter X Cloud Firestore
- javascript - 如何在 React 中过滤传入的道具?
- python - 将用户输入数据保存在 kivy 中并存储以供以后使用/分析 python
- javascript - 制作一个 js 小书签,在新窗口中打开网站并使其全屏显示(mac ver)
- html - 如果嵌入另一个标签,Chrome 和 Edge 是否会停止计算容器的预期行为?
- javascript - Node和npm在执行JS文件时抛出错误?
- amazon-web-services - 如何将数组作为环境变量放入 boto3 Lambda 函数
- python - 为本地工作 git 存储库创建一个 requirements.txt,而不用 .py 代码对导入进行 grepping