首页 > 解决方案 > 堆排序打印出 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 函数有问题,但我就是想不通。

您的帮助将不胜感激。

标签: c

解决方案


推荐阅读