堆排序

来源:互联网 发布:支持向量机算法步骤 编辑:程序博客网 时间:2024/05/16 14:55
#include <iostream.h>
#include <malloc.h>
typedef struct
{
int length;
int *elem;
}HeapType;
void Create(HeapType &H)
{
int i;
cout<<"please input the length of the data:"<<endl;
cin>>H.length;
H.elem=(int *)malloc((H.length+1)*sizeof(int));
cout<<"please input the data:"<<endl;
for(i=1;i<=H.length;i++)
cin>>H.elem[i];
}
void Print(HeapType H)
{
int i;
for(i=1;i<=H.length;i++)
cout<<H.elem[i]<<"  ";
cout<<endl;
}
void HeapAjust(HeapType &H,int s,int m)
{
int rc,j;
rc=H.elem[s];
for(j=2*s;j<=m;j*=2)
{
if(j<m && H.elem[j]<H.elem[j+1]) ++j;
if(!(rc<H.elem[j])) break;
H.elem[s]=H.elem[j];
s=j;
}
H.elem[s]=rc;
}
void HeapSort(HeapType &H)
{
int i;
for(i=H.length/2;i>0;--i)
HeapAjust(H,i,H.length);
for(i=H.length;i>1;--i)
{
H.elem[0]=H.elem[i];
H.elem[i]=H.elem[1];
H.elem[1]=H.elem[0];
HeapAjust(H,1,i-1);
}
}
void main()
{
HeapType H;
Create(H);
Print(H);
HeapSort(H);
Print(H);
}