归并排序 - 对一个数组进行排序

 

第一步:做数组的拆分

    //归并排序
    public static void sort(int[] arr){
        int[] tmp = new int[arr.length];
        int left = 0 ;
        int right = arr.length-1 ;
        sortMerge(arr , left , right , tmp);

    }

    public static void sortMerge(int[] arr , int left , int right , int[] tmp){
        if(left < right){
            int mid = (left +  right) / 2 ;
            sortMerge(arr , left , mid , tmp);
            sortMerge(arr , mid+1 , right , tmp);
            merge(arr , left , mid , right , tmp);
        }

    }

第二步:排序

这一步需要两个指针:第一个指针是前面数组的初始指针 , 第二个指针是另外一个数组的初始指针

int i = left ; //左指针
int j = mid+1 ; //右指针

做排序:

    public static void merge(int[] arr , int left , int mid , int right , int[] tmp){
        int i = left ; //左指针
        int j = mid+1 ; //右指针
        int t = 0 ;//数组临时指针
        while (i <= mid && j <= right){
            if(arr[i] <= arr[j]){
                tmp[t++] = arr[i++];
            }else{
                tmp[t++] = arr[j++];
            }
        }
        while (i <= mid){
            tmp[t++] = arr[i++];
        }
        while (j <= right){
            tmp[t++] = arr[j++];
        }

        t = 0 ;
        while (left <= right){
            arr[left ++] = tmp[t++];
        }
    }

全部代码:

public class MergeSort {

    public static void main(String[] args) {
        int[] arr = {8,7,6,5,4,3,2,1} ;
        sort(arr);
        System.out.println(Arrays.toString(arr));
    }
    public static volatile int index = 1 ;

    //归并排序
    public static void sort(int[] arr){
        int[] tmp = new int[arr.length];
        int left = 0 ;
        int right = arr.length-1 ;
        sortMerge(arr , left , right , tmp);

    }

    public static void sortMerge(int[] arr , int left , int right , int[] tmp){
        if(left < right){
            int mid = (left +  right) / 2 ;
            sortMerge(arr , left , mid , tmp);
            sortMerge(arr , mid+1 , right , tmp);
            merge(arr , left , mid , right , tmp);
        }

    }

    public static void merge(int[] arr , int left , int mid , int right , int[] tmp){
        int i = left ; //左指针
        int j = mid+1 ; //右指针
        int t = 0 ;//数组临时指针
        while (i <= mid && j <= right){
            if(arr[i] <= arr[j]){
                tmp[t++] = arr[i++];
            }else{
                tmp[t++] = arr[j++];
            }
        }
        while (i <= mid){
            tmp[t++] = arr[i++];
        }
        while (j <= right){
            tmp[t++] = arr[j++];
        }

        t = 0 ;
        while (left <= right){
            arr[left ++] = tmp[t++];
        }
    }

}
全部代码

 

posted @ 2019-03-27 19:37  niutao  阅读(1802)  评论(0编辑  收藏  举报