gpt4 book ai didi

c - 堆排序算法 CLRS

转载 作者:行者123 更新时间:2023-11-30 17:13:21 27 4
gpt4 key购买 nike

我正在根据 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]);
*/
}

最佳答案

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

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

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

关于c - 堆排序算法 CLRS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30898881/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com