import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import java.util.*;

public class HeapSort2 extends JApplet {
int heap[];
JButton sort;
JTextArea ta;
int size;
 
 

public String getHeap(){
String tmp="";
for(int k=1;k<=19;k++){
 tmp=tmp+"  "+heap[k];
 if(k%10==0)
    tmp=tmp+'\n';}
return tmp;
}
public void swap(int x[],int a,int b){
 int tmp=x[a];
 x[a]=x[b];
 x[b]=tmp;
}//swap
public void init(){
Random thing=new Random();
sort =new JButton("sort");
ta=new JTextArea(20,50);
heap=new int[20];
for(int j=1;j<20;j++)
  heap[j]=thing.nextInt(1000);
 

 Container c=getContentPane();
 c.setLayout(new BorderLayout());
 c.add(ta,BorderLayout.CENTER);
 c.add(sort,BorderLayout.SOUTH);
 ta.setText(getHeap());
 sort.addActionListener(new ActionListener(){
  public void actionPerformed(ActionEvent e){
   size=19;
ta.append("\nsort\n");
   initialize();
   heapSort();
   ta.append(getHeap());
  }
 }
 );

}

public void initialize(){
for(int root=size/2;root>=1;root--)
   {putThisElementInHeap(root);}
}

public void putThisElementInHeap(int root){
int rootElt=heap[root];
   int child=2*root;
   while(child<=size)
       {if(child<size&&heap[child]<heap[child+1])child++;
       if(rootElt>=heap[child])break;
       heap[child/2]=heap[child];
       child*=2;}
   heap[child/2]=rootElt;
}

public void heapSort(){
while(size>1){
swap(heap,1,size--);
putThisElementInHeap(1);}
  }
}