Sunday, February 10, 2013

MergeSort

import java.util.*;

public class mergesort
{
    static int a;
    static int[] arry;
    static int[] temp;
    public static void main(String [] args)
    {
        mergesort mrg=new mergesort();
        mrg.readarray();
        mrg.mergesort(0,a-1);
        print(a);
    }
   

    public void readarray()
    {
        Scanner scn=new Scanner(System.in);
        System.out.println("Please enter your length of your Array list");
        this.a=scn.nextInt();
        arry=new int[a];
        for(int i=0;i<a;i++)
        {
            System.out.println("please enter your "+(i+1)+" element");
            arry[i]=scn.nextInt();
        }
    }
   
    void mergesort(int low,int high)
    {
        if(low<high)
        {
        int mid=(low+high)/2;
            mergesort(low,mid);
            mergesort(mid+1,high);
            merge(low,mid,high);
        }
   
    }
   
    void merge(int low,int mid,int high)
    {
        int i=low,j=low,k=mid+1,l;
        temp=new int[a];
        while((i<=mid)&&(j<=high))
        {
            if(arry[i]<=arry[k])
            {
                temp[j]=arry[i];
                i++;
            }
            else
            {
                    temp[j]=arry[k];
            }
            j++;
        }
        if(k<=high) for(l=j;l<=high;l++)
                    {
                        temp[j]=arry[l];
                        j++;
                    }
            else
            {
                for(l=i;l<=mid;i++)
                {
                    temp[j]=arry[i];
                    j++;
                }
            }
           
        for(int p=low;p<=high;p++)
        {
            arry[p]=temp[p];
        }
    }
   
    void print(int high)
    {
        for(int i=0;i<=high-1;i++)
        {
        System.out.print(arry[i]+" ");
        }
    }
   
}