【Java】十大排序算法之归并排序

归并排序

原数组:5, 7, 8, 3, 1, 2, 4, 6


5,7,8,3 | 1,2,4,6(第一步将数组一分为二,即为左右两边)


5,7 | 8,3 | 1,2 | 4,6(第二步左右两边都循环一分为二直到只有一个元素停止,之后进行排序)


5,7 | 3,8(即左边的两边排序好) 1,2 | 4,6(即右边的两边排序好)


3,5,7,8(即左边都排序好) 1,2,4,6(即右边都排序好)


1,2,3,4,5,6,7,8(全部排序好)

import cn.hutool.core.util.ArrayUtil;

import java.util.Arrays;

public class MergeSortTest {

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

    public static void mergeSort(int[] arr, int[] temp, int left, int right) {
        if (left < right) {
            // 取中间点索引,为了防止left不为0的情况,不使用(left+right)/2,
            int center = left + (right - left) / 2;
            mergeSort(arr, temp, left, center);
            mergeSort(arr, temp, center + 1, right);
            merge(arr, temp, left, center, right);
        }
    }

    public static void merge(int[] arr, int[] temp, int left, int center, int right) {
        int i = left;
        int j = center + 1;
        for (int k = left; k <= right; k++) {
            if (i > center) {
                temp[k] = arr[j++];
            } else if (j > right) {
                temp[k] = arr[i++];
            } else if (arr[j] > arr[i]) {
                temp[k] = arr[i++];
            } else {
                temp[k] = arr[j++];
            }
        }
        for (int k = left; k <= right; k++) {
            arr[k] = temp[k];
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值