Java数据结构和算法-归并排序

归并排序:

归并排序(MERGE-SORT)是利用归并的思想实现的排序方法,该算法采用经典的分治(divide-and-conquer)策略(分治法将问题(divide)成一些小的问题然后递归求解,而治(conquer)的阶段则将分的阶段得到的各答案"修补"在一起,即分而治之)。

可以看到这种结构很像一棵完全二叉树,本文的归并排序我们采用递归去实现(也可采用迭代的方式去实现)。阶段可以理解为就是递归拆分子序列的过程,递归深度为log2n。

归并排序是稳定排序,它也是一种十分高效的排序,能利用完全二叉树特性的排序一般性能都不会太差。java中Arrays.sort()采用了一种名为TimSort的排序算法,就是归并排序的优化版本。从上文的图中可看出,每次合并操作的平均时间复杂度为O(n),而完全二叉树的深度为|log2n|。总的平均时间复杂度为O(nlogn)。而且,归并排序的最好,最坏,平均时间复杂度均为O(nlogn)。

归并排序Java实现:

package com.algorithm.sort;

public class MergeSort {
    public static void main(String[] args) {
        int[] a={19,2,3,90,67,33,-7,24,56,34,5};
        int left=0;
        int right=a.length-1;

        if(left<right){
            mergeSort(a,left,right);
        }
        for(int num:a){
            System.out.print(" "+num);
        }
       
    }

    private static void mergeSort(int[] a, int left, int right) {

        if(left<right){
            int mid=(left+right)/2;
            mergeSort(a,left,mid);
            mergeSort(a,mid+1,right);
            merge(a,left,mid,right);
        }
    }

    private static void merge(int[] a, int left, int mid, int right) {
        int[] tempArray=new int[a.length];
        int temp=left;
        int n=left;
        int rightStart=mid+1;

        while (left<=mid&&rightStart<=right){
            if(a[left]<=a[rightStart]){
                tempArray[temp++]=a[left++];
            }
            if (a[rightStart]<a[left]) {
                tempArray[temp++]=a[rightStart++];
            }
        }
        while(left<=mid){
            tempArray[temp++]=a[left++];
        }
        while(rightStart<=right){
            tempArray[temp++]=a[rightStart++];
        }
        while (n<=right){
            a[n]=tempArray[n++];
        }

    }
}
输出: -7 2 3 5 19 24 33 34 56 67 90

链接:https://www.cnblogs.com/chengxiao/p/6194356.html

猜你喜欢

转载自blog.csdn.net/Colin_Qichao/article/details/81433653