标签:heapsort iostream str cpp class fine [1] -- n个元素
#include <iostream.h>
#define N 8
int a[]={0,39,21,40,92,29,11,32,9};
void Adjust(int i,int last)
{
int k=2*i;
int t=a[i],tag=1;
while(k<=last&&tag)
{
if(k<last&& a[k]>a[k+1]) k++;
if(t>a[k])
{
a[i]=a[k];
i=k;
k=2*i;
}
else
tag=0;
}
a[i]=t;
}
void disp( int n)
{
for (int i=0;i<=N;i++)
cout<<a[i]<<‘\t‘;
cout<<endl;
}
void HeapSort(int n)
{
int t;
for(int i=n/2;i>=1;i--)//build heap;
{
Adjust(i,n);
}
while(n>1)
{
disp(8);
t=a[1];//交换堆的第一与最后元素
a[1]=a[n];
a[n]=t;
// disp(8);cout<<n;
Adjust(1,n-1);//交换后第n个元素就不要考虑了
cout<<endl;
n--;
}
}
void main()
{
HeapSort(8);
disp(8);
}
标签:heapsort iostream str cpp class fine [1] -- n个元素
原文地址:http://www.cnblogs.com/ewitt/p/6895941.html