这是我的程序,它使用三个函数来执行堆排序。我无法弄清楚问题出在哪里。如果有人愿意帮忙,会很高兴。
这两个函数计算索引的左侧和右侧
int left(int i)
{return(2*i+1);}
int right(int i)
{return(2*i+2);}
此处的最大值是最大数组索引。a 是数组i 是索引
void maxheapify(int i,int *a,int max)
{
if(i>(max-1)/2)
return;
else
{
int big=0,temp=0;
if(a[i]<a[left(i)])
big=left(i);
if(right(i)<=max && a[i]<a[right(i)])
big=right(i);
if(big==i)
return;
else
{
temp=a[big];
a[big]=a[i];
a[i]=temp;
maxheapify(big,a,max);
}
}
}
void buildmaxheap(int *a,int max)
{
int i;
for(i=0;i<=(max-1)/2;i++)
maxheapify(i,a,max);
}
void heapsort(int *a,int max)
{
int j=0,temp=0;
for(j=max;j>0;j--)
{
buildmaxheap(a,j);
temp=a[0];
a[0]=a[j];
a[j]=temp;
}
}
关于你的代码,我注意到一件事。您的左右条件都可以一个接一个地满足。导致右移动到父级,但不能保证右(i)>=左(i)。我觉得这可能会在堆完成后导致一些排序问题