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

import java.util.*;

public class MergeSort extends JApplet implements ActionListener{
int list[],aux[];
JButton sort;
JTextArea ta;
int size;
final int max=20;
 

public String getContents(int[]list){
String tmp="";
for(int k=0;k<max;k++){
 tmp=tmp+"  "+list[k];
 }
return tmp;
}

public void init(){
Random thing=new Random();
sort =new JButton("sort");
ta=new JTextArea(50,100);
list=new int[max];
aux=new int[max];
for(int j=0;j<max;j++)
  list[j]=thing.nextInt(1000);
 

 Container c=getContentPane();
 c.setLayout(new BorderLayout());
 c.add(ta,BorderLayout.CENTER);
 c.add(sort,BorderLayout.SOUTH);
 ta.setText(getContents(list));
 sort.addActionListener(this);}

public void actionPerformed(ActionEvent e){

ta.append("\nsort\n");

System.arraycopy(list,0,aux,0,aux.length);
   mergeSort(aux,list,0,list.length);
ta.append("\nback from sorting\n ");
ta.append(getContents(list));
  }
 
 

public void mergeSort(int src[],int dest[],int low,int high){
ta.append("\nin sorting routine\n");
ta.append(getContents(list));
int len=high-low;
if(len<7){
   for(int i=low;i<high;i++)
     for(int j=i;j>low&&dest[j-1]>dest[j];j--)
       swap(dest,j,j-1);
 return;}
int mid=(low+high)/2;
mergeSort(dest,src,low,mid);
mergeSort(dest,src,mid,high);
if(src[mid-1]<src[mid]){System.arraycopy(src,low,dest,low,len);return;}
for(int i=low,p=low,q=mid;i<high;i++)
   if(q>=high||(p<mid&&src[p]<=src[q]))dest[i]=src[p++];
   else dest[i]=src[q++];

}//merge

public void swap(int x[],int a,int b){
 int tmp=x[a];
 x[a]=x[b];
 x[b]=tmp;
}//swap
}// class