归并排序(Java)

public class Merge_Sort {
    public static void main(String[] args)
    {
        int[] A ={3,1,2,4,6,7,5,3};
        Merge_sort(A,0,7);
        for(int i=0;i<A.length;i++)
        {
            System.out.print(A[i]);
            System.out.print(' ');
        }
    }

    public static void Merge_sort(int[] A,int p,int r)
    {
        int q;
        if(p<r)
        {
            q = (p+r)/2;
            Merge_sort(A,p,q);
            Merge_sort(A,q+1,r);
            Merge(A,p,q,r);
        }
    }
    public static void Merge(int[] A,int p,int q,int r)
    {
        int n1 = q-p+1;
        int n2 = r-q;
        int L[]= new int[n1];
        int R[] = new int[n2];
        int i,j;
        for(i=0;i<n1;i++)
            L[i] = A[p+i];
        for(i=0;i<n2;i++)
            R[i] = A[q+i+1];
        //L[n1-1] = 999999;
        //R[n2-1] = 999999;
        i=0; j=0;
        for(int k=p;k<=r;k++)
        {

            if(i<L.length && j<R.length && L[i]<=R[j])
            {
                A[k] = L[i];
                i = i+1;
            }
            else if(i<L.length && j<R.length && L[i]>R[j])
            {
                A[k] = R[j];
                j = j+1;
            }
            else if(i>=L.length && j<R.length)
            {
                A[k] = R[j];
                j = j+1;
            }
            else if(i<L.length && j>=R.length)
            {
                A[k] = L[i];
                i = i+1;
            }
        }
    }
}

 

posted @ 2017-04-22 21:18  dear_diary  阅读(249)  评论(0编辑  收藏  举报