Sunday, January 29, 2012

MergeSort

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package mergesort;

import javax.swing.JOptionPane;

/**
 *
 * @author KAPILAN
 */
public class MergeSort {
    int[] array;
    int size;
   public MergeSort(int n){
       size=n;
       array=new int[size];
       for(int i=0;i<size;i++){
           array[i]=(int) Math.round(Math.random()*900+100);
       }
   }
   public void mergesort(){
       mergesort(0,size-1);
   }
   public void mergesort(int l,int r){
       if(l<r){
           int mid=(l+r)/2;
           mergesort(l,mid);
           mergesort(mid+1,r);
           merge(l,mid,r);
       }
   }

    private void merge(int l, int m, int r) {
       int i=l; int j=m+1; int k=0;
       int[] temp=new int[r-l+1];
       while(i<=m && j<=r){
           if(array[i]>array[j])temp[k++]=array[i++];
           else temp[k++]=array[j++];
       }
       while(i<=m) temp[k++]=array[i++];
       while(j<=r) temp[k++]=array[j++];
       for(k=0;k<r-l+1;k++) array[l+k]=temp[k];
    }
public void display(){
    int psize=15;
    String ds="";
    int rows=(size-1)/psize+1;
    int k=0;
    int i,row;
            for(row=1;row<rows;row++){
                for(i=0;i<psize;i++)
                    ds=ds+" : "+array[k++];
                    ds=ds+"\n";

            }
    for(i=k;i<size;i++)ds=ds+" : "+array[i];
    JOptionPane.showMessageDialog(null,ds,"contents of the array",1);
    System.out.print(ds);
}
public static void main(String[] a){
     MergeSort s1=new  MergeSort(20);
     System.out.println("Before Sort");
     s1.display();
     System.out.println();
     s1.mergesort();
     System.out.println("After Sort");
     s1.display();
}
}
/*Before Sort
 : 594 : 646 : 503 : 606 : 156 : 333 : 574 : 878 : 284 : 884 : 742 : 941 : 768 : 517 : 269
 : 563 : 853 : 783 : 989 : 117
After Sort
 : 989 : 941 : 884 : 878 : 853 : 783 : 768 : 742 : 646 : 606 : 594 : 574 : 563 : 517 : 503
 : 333 : 284 : 269 : 156 : 117*/

No comments:

Post a Comment