【问题标题】:Heapsort algorithm CLRS堆排序算法 CLRS
【发布时间】:2025-10-22 16:00:01
【问题描述】:

我正在根据 CLRS 在 C 中实现堆排序算法。但是我无法获得排序的输出。你能看看我的代码有什么问题吗?函数 maxheapbuildmaxheap 有效。我无法弄清楚代码有什么问题。

代码应该对数组元素进行堆排序。我觉得heapsort() 函数中有一个错误,因为maxheapbuildmaxheap 工作得很好。

我得到的最终输出是

1 1 1 1 2 1 2 2 1 1

但预期的输出应该是

1 2 3 4 7 8 9 10 14 16

代码:

#include<stdlib.h>
#include<stdio.h>

#define maxn 11
int n=10;

int parent(int i)
{
    return i/2;
}

int left(int i)
{
    return 2*i+0;
}

int right(int i)
{
    return 2*i+1+0;
}

void  max_heap(int x[],int i,int heapsize)
{
    int largest;
    int l=left(i);
    int r=right(i);

    if (l<=heapsize &&  x[l]>x[i]){
        largest=l;
    }
    else
    {
        largest=i;
    }
    if (r<=heapsize && x[r]>x[largest]){
        largest=r;
    }
    if (largest!=i)
    {
        int s=x[i];x[i]=x[largest];x[largest]=s;
        max_heap(x,largest,heapsize);
    }
}

void buildmaxheap(int x[],int heapsize)
{

    int i;
    for(i=5;i>=1;i--)
        max_heap(x,i,heapsize);

}

void heapsort(int x[])
{
    buildmaxheap(x,10);
    int i,t,heapsize=10;
    for(i=10;i>=2;i--)
    {
        int s=x[i];x[1]=x[i];x[i]=s;

        heapsize--;
        /*
         printf("%d",heapsize);
         */
        max_heap(x,i,heapsize);
    }
    for(i=1;i<=10;i++)
        printf("%d\t",x[i]);

}

int main()
{
    int x[maxn],i;
    x[1]=16;
    x[2]=4;
    x[3]=10;
    x[4]=14;
    x[5]=7;
    x[6]=9;
    x[7]=3;
    x[8]=2;
    x[9]=8;
    x[10]=1;
    heapsort(x);
    /*
     for(i=1;i<=10;i++)
     printf("%d\t",x[i]);
     */
}

【问题讨论】:

  • 究竟是什么不工作?
  • 好吧,它浪费了 x[0]。开始。我不信任具有“1..”索引的 C 数组,即使声明的开头尺寸过大:(
  • 堆排序函数。这是我在堆排序函数后打印数组后得到的输出:1 1 1 1 2 1 2 2 1 1
  • 1.使用调试器。 2. C 中的数组是从零开始的,而不是从一开始的。不要逃避这个事实;拥抱它。 3. 具有堆属性potentially 的数组中索引i 处的元素在槽2*i+12*(i+1) 有子元素,受整个序列长度N 的限制(意味着如果那些计算为等于或大于N 的值,则该孩子不存在)。
  • 您需要在问题中添加更多详细信息,否则将作为题外话关闭:Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers

标签: c algorithm heapsort clrs


【解决方案1】:

堆排序中缺乏逻辑。任何排序算法都必须比较 2 个值,并为小于做一件事,另一件事为更大,如果相同则别管它。目前,您会自动多次交换索引为 1 的比较器。

我不清楚为什么它会丢失数字导致随机的 1 和 2,但它看起来很糟糕,我不会再给你时间,直到你再试一次。

在c中,数组索引从0开始,在这个10个节点的小困境中不要避免它,这没什么。但是,如果您不开始自动将零视为第一,那么您将付出很大的代价。

【讨论】:

    【解决方案2】:

    这一行:

    int s=x[i];x[1]=x[i];x[i]=s;
    

    看起来它正在尝试进行交换,但它搞混了。查看索引并考虑顺序。

    在你修复它之后,还有另一个错误。我没有这本书,所以我不知道它到底告诉你做什么,但我相信你需要在删除一个元素后从 从根 开始修复堆属性,并且你的代码没有这样做。

    【讨论】: