归并排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_26533265/article/details/51997691

归并排序

public class Test {

    public  void  Sort(int[] num){
        if(num==null||num.length<=0){
            return;
        }
        mergeSort(num,0,num.length-1);

    }

    public void mergeSort(int[] data ,int left,int right){
        if(left>=right){
            return;
        }
        int center=(left+right)/2;
        mergeSort(data, left, center);
        mergeSort(data, center+1, right);
        Merge(data,left,center,right);

    }
    public void Merge(int[] data,int left,int center,int right){
        int [] tmpArray=new int[data.length];
        int tmp=left;
        int third=left;
        int mid=center+1;
        while(left<=center&&mid<=right){
            if(data[left]<data[mid]){
                tmpArray[third++]=data[left++];
            }else{
                tmpArray[third++]=data[mid++];
            }
        }
        while (left<=center) {
        tmpArray[third++]=data[left++];

        }

        while(mid<=right){
            tmpArray[third++]=data[mid++];
        }

        while(tmp<=right){
            data[tmp]=tmpArray[tmp++];
        }

    }


    public static void main(String[] args){
         int[] data = new int[]{ 5, 3, 6, 2, 1, 9, 4, 8, 7 } ;  

            new Test().Sort(data); 
            for (int i = 0; i < data.length; i++) {  
                System.out.print(data[i] + "\t");  
            }  
            System.out.println();  
    }

}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页