Java中的合并排序算法

合并排序是一种分而治之的算法,因为该算法会将原始数组拆分为较小的逻辑部分。 可以利用循环或递归来实现该算法。 这两个不同的阶段是分裂阶段,其次是合并阶段。

分裂阶段:将数组分为两个未排序的数组。 将每个拆分数组连续拆分为较小的数组,直到仅存在多个单个元素数组。 单元素数组被排序,因为它们中只有一个元素。

合并阶段:现在,每个单个元素数组都合并回到更大的数组中。 在合并阶段,将两个数组合并,以便在新的较大排序数组中对元素进行排序。 重复此过程,直到剩下单个排序数组为止。 这不是就地算法,因为使用了临时数组。

Algorithm Classification

下表包含有关合并排序算法分析的信息。 它根据时间复杂度以及空间复杂度定义了最坏,平均和最佳情况。

属性值类排序算法类ification内部非原位稳定算法数据结构数组时间复杂度:最佳Ω(n log(n))时间复杂度:平均值Θ(n log(n))时间复杂度:最差O(n log(n))空间复杂性:最差上)

Please use the following link for an explanation on Big-O notation and what is good, fair and bad.

Merge Sort In Java

public final class MergeSort {

    public void sort(int[] collection) {
        if (collection != null) {
            mergeSort(collection, 0 , collection.length);
        } else {
            throw new IllegalArgumentException("Input paramenter for array to sort is null.");
        }
    }

    public  void mergeSort(int[] collection, int minIndex, int maxIndex) {
        if (maxIndex - minIndex < 2) {
            return;
        }

        int centre = (minIndex + maxIndex) / 2;
        mergeSort(collection, minIndex, centre);
        mergeSort(collection, centre, maxIndex);
        mergeBack(collection, minIndex, centre, maxIndex);       
    }

    public void mergeBack(int[] collection, int minIndex, int centre, int maxIndex) {
        if (collection[centre - 1] <= collection[centre]) {
            return;
        }
        int tempMinIndex = minIndex;
        int tempCentre = centre;

        int tempIndex = 0;
        int[] tempArray = new int[maxIndex - minIndex];

        while ((tempMinIndex < centre) && (tempCentre < maxIndex)) {
            if(collection[tempMinIndex] <= collection[tempCentre]) {
                tempArray[tempIndex++] = collection[tempMinIndex++];    
            } else {
                tempArray[tempIndex++] = collection[tempCentre++];
            }
        }

        System.arraycopy(collection, tempMinIndex, collection, minIndex + tempIndex, centre - tempMinIndex);
        System.arraycopy(tempArray, 0, collection, minIndex, tempIndex);
    }   
}
Sample Code (GitHub)

可以在此处查看MergeSort类的详细信息。 可以在此处查看MergeSort JUnit Test类的详细信息。

Conclusion

合并排序算法构成较大的一组排序算法的一部分。 通过经验学习是我创建这篇关于Java合并排序算法实现的帖子的原因。 我了解了很多其他人如何解决其他语言(包括Java中的不同实现)的合并排序算法的知识。

The post Merge Sort Algorithm in Java appeared first on Code2Bits.

from: https://dev.to//code2bits/merge-sort-algorithm-in-java-5gfd

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值