//堆排序 #include <iostream.h> void main() { int a[12]={2,4,6,34,31,24,65,37,87,68,90,23}; int b[12]; for (int i=0;i<12;i++) { b[i]=a[i]; int temp=i; while (temp-1>=0) { if (b[(temp-1)/2]<b[temp]) { int x=b[(temp-1)/2]; b[(temp-1)/2]=b[temp]; b[temp]=x; temp=(temp-1)/2; } else { break; } } } for (int j=11;j>=0;j--) { cout<<b[0]<<" "; b[0]=b[j]; int temp=0; while (2*temp+1<j) { if (2*temp+2<j) { int max=b[temp]; int index=temp; if (max<b[2*temp+1]) { max=b[2*temp+1]; index=2*temp+1; } if (max<b[2*temp+2]) { max=b[2*temp+2]; index=2*temp+2; } if (index==temp) { break; } else { b[index]=b[temp]; b[temp]=max; temp=index; } } else { int max=b[temp]; int index=temp; if (max<b[2*temp+1]) { max=b[2*temp+1]; index=2*temp+1; } if (index==temp) { break; } else { b[index]=b[temp]; b[temp]=max; temp=index; } } } } cout<<endl; }