对于数组输入 2 5 8 3 4 6 我得到 2 4 5 3 8 6 我正在尝试实现堆排序,我是初学者,我不知道这里会出现什么错误,我只是想通过构建堆并将最后一个元素与最大的第一个索引交换来实现堆排序的逻辑元素,从而减小数组的大小。
#include<stdio.h>
#include<conio.h>
构建一个获取起始索引中最高的元素
heapify(int *a,int i,int no)
{
int largest = i;
int left = 2*i;
int right = 2*i+1;
if(left<=no && a[left]>largest)
{
largest=left;
}
if(right<=no && a[right]>largest)
{
largest=right;
}
if(largest!=i)
{
int temp=a[largest];
a[largest]=a[i];
a[i]=temp;
heapify(a,largest,no);
}
}
对数组中的元素进行堆排序
heapsort(int *a,int no)
{
while(no>1)
{
int temp=a[1];
a[1]=a[no];
a[no]=temp;
--no;
heapify(a,1,no);
}
}
打印数组中的元素
printarr(int *a,int no)
{
int i=1;
for(;i<=no;i++)
printf("%d",a[i]);
}
这是主要功能。
int main()
{
int i,j,k,no,size;
printf("Enter the no of elements");
scanf("%d",&no);
int a[no+1];
size=no;
for(i=1;i<=no;i++)
{
scanf("%d",&a[i]);
}
printarr(a,no);
j=no/2;
for(i=j;i>0;--i)
{
heapify(a,i,no);
}
heapsort(a,no);
printarr(a,no);
getch();
return 0;
}
最佳答案
你在 heapify 函数中比较索引和数组值
if(left<=no && a[left]>largest)
和
if(right<=no && a[right]>largest)
应该是
if(left<=no && a[left]>a[largest])
和
if(right<=no && a[right]>a[largest])
关于c - 堆排序 : how to correct my coding and to implement my logic?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25378032/