八大排序算法之归并排序—Java

#归并排序
归并排序采用的经典的分治策略,主要分为分和治两部分,时间复杂度为O(nlog n),空间复杂度为O(n)。主要思想如下图,(该图来自韩顺平老师的课件)
在这里插入图片描述
该算法的分部分是为了化简问题将大的数组不断的递归划分成两部分;
治的部分是为了将两个有序数组合并到一起,需要注意的是每次合并的前提是左右两个数组是有序的。

public class MergeSortDemo {
    public static void main(String[] args) {
        int[] arr = {8, 4, 5, 7, 1, 3, 6, 2};
        int[] temp = new int[arr.length];
        mergeSort(arr, 0, arr.length - 1, temp);
        System.out.println(Arrays.toString(arr));
    }

    /**
     * 
     * @param arr 待排序数组
     * @param left 左节点
     * @param right 右边节点
     * @param temp 临时矩阵
     */
    public static void mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            //1.分
            int mid = (left + right) / 2;
            mergeSort(arr, left, mid, temp);//向左递归
            mergeSort(arr, mid + 1, right, temp);//向右递归
            //2.治
            merge(arr, left, mid, right, temp);

        }
    }

    /**
     * 将列表的两部分内容合并到一起
     *
     * @param arr 待排序数组
     * @param left  左节点
     * @param mid   中间节点
     * @param right 右边节点
     * @param temp  临时矩阵
     */
    public static void merge(int[] arr, int left, int mid, int right, int[] temp) {
        int count = -1;//记录存入temp中的数据长度
        int leftIndex = left;
        int rightIndex = mid + 1;
        //1.将左右两边的数据按规则填充到temp数组中,直到一边处理完毕为止
        while (leftIndex <= mid && rightIndex <= right) {
            count++;
            if (arr[leftIndex] <= arr[rightIndex]) {
                temp[count] = arr[leftIndex];
                leftIndex++;
            } else {
                temp[count] = arr[rightIndex];
                rightIndex++;
            }
        }

        //2.将剩余的元素加入到temp中
        while (leftIndex <= mid) {
            count++;
            temp[count] = arr[leftIndex];
            leftIndex++;
        }
        while (rightIndex <= right) {
            count++;
            temp[count] = arr[rightIndex];
            rightIndex++;
        }
        //将3.temp的元素拷贝到arr中
        for (int i = 0; i <= count; i++) {
            arr[i + left] = temp[i];
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值