基本思想:

  归并排序法是分治法的典型实例,分为分割和归并两部分。

  把一个数组分为大小相近的子数组(分割),分别把子数组排好序后,通过合成一个大的排好序的数组(归并)。

 实例:

   先分割成每个子序列只有一个元素,然后再两两归并。

  

 归并排序是稳定的排序算法,时间复杂度为:O(NlogN).

 Java实现:

 

package sort;

public class MergeSort {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new MergeSort().run();
    }
    public void run(){
        
        int a[] = {3,1,5,7,2,4,9,6};
        int len = a.length;
        sort(a,0,len-1);
        for(int i=0;i<len;i++){
            System.out.print(a[i]+" ");
        }
    }
    /**
     * 归并排序  稳定的
     * 基本思想
     * 将两个或两个以上有序表合并成一个新的有序表
     * 即把待排序序列分成若干个子序列,每个子序列是有序的,然后在把有序子序列合并为整体有序序列
     */
    public void sort(int arr[],int low,int high){
        if(low == high){
            return;
        }
        int mid = (low+high)/2;
        if(low<high){
            /**
             * 对左边排序
             */
            sort(arr,low,mid);
            /**
             * 对右边排序
             */
            sort(arr,mid+1,high);
            /**
             * 左右归并
             */
            merge(arr,low,mid,high);
        }
    }
    public void merge(int[] arr,int low,int mid,int high){
        int [] temp = new int[high-low+1];
        /**
         * 左指针
         */
        int i = low;
        /**
         * 右指针
         */
        int j = mid+1;
        int k=0;
        /**
         * 先把较小的数移到新数组中
         */
        while(i<=mid && j<=high){
            if(arr[i]<arr[j]){
                temp[k++] = arr[i++];
            }else{
                temp[k++] = arr[j++];
            }
        }
        /**
         * 把左边剩余的数移入新数组
         */
        while(i<=mid){
            temp[k++] = arr[i++];
        }
        /**
         * 把右边剩余的数移入新数组
         */
        while(j<=high){
            temp[k++] = arr[j++];
        }
        /**
         * 用新数组中的数覆盖arr数组
         */
        for(int k2=0;k2<temp.length;k2++){
            arr[k2+low] = temp[k2];
        }
    }
}

 

 结果展示:

 

  (本文仅供学习交流,如有更好的思路,欢迎留下意见供大家探讨学习~)