import java.io.*;
class heap_sort
{
static int heapsize;
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Heap size??");
int n=Integer.parseInt(br.readLine());
int i,a[]=new int[n],temp;
for(i=0;i<n;i++)
a[i]=Integer.parseInt(br.readLine());
heapsize=a.length;
maxheap(a);
for(i=n-1;i>=1;i--)
{
temp=a[0];
a[0]=a[i];
a[i]=temp;
heapsize--;
maxheapify(a,0);
}
}
public static void maxheap(int a[])
{
int i;
for(i=(heapsize-1)/2;i>=0;i--)
a=maxheapify(a,i);
}
public static int[] maxheapify(int a[],int i)
{
int l=2*i+1;
int r=2*(i+1);
int largest,temp;
if(l<heapsize&&a[l]>a[i])
largest=l;
else
largest=i;
if(r<heapsize&&a[r]>a[largest])
largest=r;
if(largest!=i)
{
temp=a[i];
a[i]=a[largest];
a[largest]=temp;
maxheapify(a,largest);
}
return a;
}
}
class heap_sort
{
static int heapsize;
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Heap size??");
int n=Integer.parseInt(br.readLine());
int i,a[]=new int[n],temp;
for(i=0;i<n;i++)
a[i]=Integer.parseInt(br.readLine());
heapsize=a.length;
maxheap(a);
for(i=n-1;i>=1;i--)
{
temp=a[0];
a[0]=a[i];
a[i]=temp;
heapsize--;
maxheapify(a,0);
}
}
public static void maxheap(int a[])
{
int i;
for(i=(heapsize-1)/2;i>=0;i--)
a=maxheapify(a,i);
}
public static int[] maxheapify(int a[],int i)
{
int l=2*i+1;
int r=2*(i+1);
int largest,temp;
if(l<heapsize&&a[l]>a[i])
largest=l;
else
largest=i;
if(r<heapsize&&a[r]>a[largest])
largest=r;
if(largest!=i)
{
temp=a[i];
a[i]=a[largest];
a[largest]=temp;
maxheapify(a,largest);
}
return a;
}
}