#include<iostream>
using namespace std;
void sift(int [],int,int);
void BuildMaxHeap(int [],int);
void Heap_sort(int [],int);
int main(void){
int heap[13]={50,41,19,81,45,25,56,61,49,10,36,15,90};
BuildMaxHeap(heap,13);
cout<<"Heap sort前:";
for(int i=0;i<13;i++)
cout<<heap[i]<<" ";
cout<<endl;
Heap_sort(heap,13);
cout<<"Heap sort後:";
for(int i=0;i<13;i++)
cout<<heap[i]<<" ";
cout<<endl;
return 0;
}
void BuildMaxHeap(int heap[],int n){
int i;
for(i=(n-2)/2;i>=0;i--)
sift(heap,i,n);
}
void sift(int a[],int i,int n){
int temp,j;
temp=a[i];
j=2*i+1;
while(j<n){
if(j+1<n&&a[j]<a[j+1])
j++;
if(temp>a[j])
break;
a[i]=a[j];
i=j;
j=2*i+1;
}
a[i]=temp;
}
void Heap_sort(int heap[],int n){
int k,temp;
while(n>1){
temp=heap[n-1];
heap[n-1]=heap[0];
heap[0]=temp;
n--;
k=(n-2)/2;
for(int i=k;k>=0;k--){
sift(heap,i,n);}
}
}
I2luY2x1ZGU8aW9zdHJlYW0+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7Cgp2b2lkIHNpZnQoaW50IFtdLGludCxpbnQpOwp2b2lkIEJ1aWxkTWF4SGVhcChpbnQgW10saW50KTsKdm9pZCBIZWFwX3NvcnQoaW50IFtdLGludCk7CgppbnQgbWFpbih2b2lkKXsKICAgIAogICAgaW50IGhlYXBbMTNdPXs1MCw0MSwxOSw4MSw0NSwyNSw1Niw2MSw0OSwxMCwzNiwxNSw5MH07CiAgICBCdWlsZE1heEhlYXAoaGVhcCwxMyk7CiAgICAgIGNvdXQ8PCJIZWFwIHNvcnTliY06IjsKICAgICAgZm9yKGludCBpPTA7aTwxMztpKyspCiAgICAgIGNvdXQ8PGhlYXBbaV08PCIgIjsgCiAgICAgIGNvdXQ8PGVuZGw7CiAgICAKICAgIEhlYXBfc29ydChoZWFwLDEzKTsKICAgIAogICAgY291dDw8IkhlYXAgc29ydOW+jDoiOwogICAgZm9yKGludCBpPTA7aTwxMztpKyspCiAgICAgY291dDw8aGVhcFtpXTw8IiAiOyAKICAgICBjb3V0PDxlbmRsOwogICAgCiAgICAgICAgIHJldHVybiAwOyAgCn0KCgp2b2lkIEJ1aWxkTWF4SGVhcChpbnQgaGVhcFtdLGludCBuKXsKICAgICAgICBpbnQgaTsKICAgICAgICBmb3IoaT0obi0yKS8yO2k+PTA7aS0tKQogICAgICAgICBzaWZ0KGhlYXAsaSxuKTsKICAgICAKICAgICB9CiAgICAgCiAgICAgCnZvaWQgc2lmdChpbnQgYVtdLGludCBpLGludCBuKXsKICAgICBpbnQgdGVtcCxqOwogICAgIHRlbXA9YVtpXTsKICAgICBqPTIqaSsxOwogICAgIAogICAgIHdoaWxlKGo8bil7CiAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgIAogICAgICAgICAgICAKICAgICAgICAgICAgaWYoaisxPG4mJmFbal08YVtqKzFdKQogICAgICAgICAgICBqKys7CiAgICAgICAgICAgIGlmKHRlbXA+YVtqXSkKICAgICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAKICAgICAgICAgICAgCiAgICAgCiAgICAgICAgICAgIGFbaV09YVtqXTsgICAgCiAgICAgICAgICAgIGk9ajsKICAgICAgICAgICAgCiAgICAgICAgICAgIGo9MippKzE7CiAgICAgICAgICAgICAKICAgICAgICAgICAgCiAgICAgfQogICAgIGFbaV09dGVtcDsKICAgICAKICAgICB9CiAgICAgCnZvaWQgSGVhcF9zb3J0KGludCBoZWFwW10saW50IG4pewogICAgIGludCBrLHRlbXA7CiAgICAgCiAgICAgd2hpbGUobj4xKXsKICAgICB0ZW1wPWhlYXBbbi0xXTsKICAgICBoZWFwW24tMV09aGVhcFswXTsKICAgICBoZWFwWzBdPXRlbXA7CiAgICAgbi0tOwogICAgIGs9KG4tMikvMjsKICAgICBmb3IoaW50IGk9aztrPj0wO2stLSl7CiAgICAgc2lmdChoZWFwLGksbik7fQogICAgIH0KICAgICAKICAgICB9