请问这个用C语言写的堆排序算法错在哪里

高桥美惠 2016-03-13 10:20:28
#include<stdio.h>
#include<math.h>

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

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

void exchange(int A[],int i,int j)
{ int temp;
temp=A[i-1]; A[i-1]=A[j-1]; A[j-1]=temp;
}

void MAX_HEAPIFY(int A[10],int i,int length,int heapsize)
{ int l,r,largest;
l=left(i); r=right(i);
if(l<=heapsize && A[l-1]>A[i-1])
largest=l;
else
largest=i;
if(r<=heapsize && A[r-1]>A[i-1])
largest=r;
if(i!=largest)
{ exchange(A,i,largest);
MAX_HEAPIFY(A,largest,length,heapsize);
}
}

void BUILD_HEAP(int A[10],int length,int heapsize)
{ for(int i=floor(length/2);i>=1;i--)
MAX_HEAPIFY(A,i,length,heapsize);
}

void HEAPSORT(int A[10],int length,int heapsize)
{ BUILD_HEAP(A,length,heapsize);
for(int i=length;i>1;i--)
{ exchange(A,1,heapsize--);
MAX_HEAPIFY(A,1,length,heapsize);
}
}

int main()
{ int A[10]={12,1,5,2,3,8,6,7,19,15},length=10,heapsize=10;
HEAPSORT(A,length,heapsize);
for(int i=0;i<10;i++)
printf("%d ",A[i]);
}
...全文
93 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
高桥美惠 2016-03-13
  • 打赏
  • 举报
回复
[code=c#include<stdio.h> #include<math.h> int left(int i) { return (i*2); } int right(int i) { return (i*2+1); } void exchange(int A[],int i,int j) { int temp; temp=A[i-1]; A[i-1]=A[j-1]; A[j-1]=temp; } void MAX_HEAPIFY(int A[10],int i,int length,int heapsize) { int l,r,largest; l=left(i); r=right(i); if(l<=heapsize && A[l-1]>A[i-1]) largest=l; else largest=i; if(r<=heapsize && A[r-1]>A[i-1]) largest=r; if(i!=largest) { exchange(A,i,largest); MAX_HEAPIFY(A,largest,length,heapsize); } } void BUILD_HEAP(int A[10],int length,int heapsize) { for(int i=floor(length/2);i>=1;i--) MAX_HEAPIFY(A,i,length,heapsize); } void HEAPSORT(int A[10],int length,int heapsize) { BUILD_HEAP(A,length,heapsize); for(int i=length;i>1;i--) { exchange(A,1,heapsize--); MAX_HEAPIFY(A,1,length,heapsize); } } int main() { int A[10]={12,1,5,2,3,8,6,7,19,15},length=10,heapsize=10; HEAPSORT(A,length,heapsize); for(int i=0;i<10;i++) printf("%d ",A[i]); }][/code]

69,368

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧