算法-合并排序

时间复杂度:o(nlog(n))
代码:

package suanfa;
//合并排序

public class hebingpaixu {

    public static void main(String[] args) {
        int a[]={1,9,8,7,5,4,2};
        int temp[]=new int[a.length];
        sort(a,temp,0,a.length-1);
        for(int i=0;i<a.length;i++)
            System.out.print(a[i]+"  ");
    }
    public static void sort(int a[],int []b,int left,int right){

        if(left<right){
            int middle=(left+right)/2;
            sort(a,b,left,middle);
            sort(a,b,middle+1,right);
            merge(a,b,left,middle,right);

        }

    }
    public static void merge(int a[],int temp[],int left,int middle,int right){
        int i=left;
        int j=middle+1;
        int k=0;
        while(i<=middle&&j<=right){
            if(a[i]<a[j])
                temp[k++]=a[i++];
            else
                temp[k++]=a[j++];

        }
        while(i<=middle){
            temp[k++]=a[i++];
        }
        while(j<=right){
            temp[k++]=a[j++];
        }
        for(int i1=0;i1<k;i1++){
            a[i1+left]=temp[i1];
        }
    }

}
原文地址:https://www.cnblogs.com/wangxiaopei/p/8551278.html