#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
void input(vector<int> &v)
{
cout<<"please enter the data:"<<endl;
int data;
v.push_back(0);
while(cin>>data)
v.push_back(data);
}
void output(const vector<int> &v)
{
for(vector<int>::const_iterator iter=v.begin()+1; iter!=v.end(); iter++)
cout<<*iter<<" ";
cout<<endl;
}
void max_heap(vector<int> &v, int heap_len, int i)
{
int larg=i;
if(2*i<=heap_len&&v[2*i]>v[larg])
larg=2*i;
if(2*i+1<=heap_len&&v[2*i+1]>v[larg])
larg=2*i+1;
if(larg!=i)
{
int temp=v[i];
v[i]=v[larg];
v[larg]=temp;
max_heap(v,heap_len,larg);
}
}
void build_heap(vector<int> &v,int heap_len)
{
for(int i=heap_len/2; i>=1; i--)
max_heap(v, heap_len, i);
}
void heapSort(vector<int>& v)
{
int heap_len=v.size()-1;
build_heap(v,heap_len); //该步的复杂度为O(n)
for(int i=heap_len; i>=2; --i) //调用n-1次max_heap的复杂度为(n-1)*(lgn)
{
int temp=v[1];
v[1]=v[heap_len];
v[heap_len]=temp;
heap_len--;
max_heap(v, heap_len, 1); //总复杂度为O(nlgn)
}
}
int main(int argc, char *argv[])
{
vector<int> v;
input(v);
build_heap(v, v.size()-1);
heapSort(v);
output(v);
system("PAUSE");
return EXIT_SUCCESS;
}