Java 归并排序(基于迭代)

最近一段时间看了一些算法相关的东西,其中有归并算法,但是大部分都是基于递归来实现的,
发现这个老兄是基于迭代来做的,原文章地址:

https://blog.csdn.net/weixin_45754452/article/details/121557330

然后在他的基础上做了一些优化。

import java.util.Arrays;

/**
 * @Description 归并排序(迭代)
 * @Author liuy-cf
 * @Date 2022/9/2 11:08
 */
public class MergeSort {

  static final int MAXIMUM_CAPACITY = 1 << 30;

  public int[] sort(int[] sources) {
    //拷贝源数据
    int[] targets = Arrays.copyOfRange(sources, 0, sources.length);
    //计算需要迭代的轮数
    int round = tableSizeFor(targets.length);
    int stepLength = 1;
    int t[];
    int[] temp = new int[targets.length];
    while (stepLength < round) {
      for (int i = 0; i < targets.length; i += stepLength * 2) {
        int index = i, left = i, right = i + stepLength;
        while ((left < i + stepLength && left < targets.length) || (right < i + stepLength * 2
            && right < targets.length)) {
          if ((left < i + stepLength && left < targets.length) && (right < i + stepLength * 2
              && right < targets.length)) {
            if (targets[left] < targets[right]) {
              temp[index++] = targets[left];
              left++;
            } else {
              temp[index++] = targets[right];
              right++;
            }
          } else if (left < i + stepLength && left < targets.length) {
            temp[index++] = targets[left];
            left++;
          } else if (right < i + stepLength * 2 && right < targets.length) {
            temp[index++] = targets[right];
            right++;
          }
        }
      }
      t = targets;
      targets = temp;
      temp = t;
      stepLength *= 2;
    }
    return targets;
  }

  /**
   * 取大于某个整数的最小2次幂,该方法取自java.util.HashMap#tableSizeFor(int)
   */
  private int tableSizeFor(int cap) {
    int n = cap - 1;
    n |= n >>> 1;
    n |= n >>> 2;
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;
    return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
  }

  public static void main(String[] args) {
    MergeSort mergeSort = new MergeSort();
    int[] nums = {16, 22, 43, 1, 7, 223, 556, 11, 1213, 98, 200, 114, 3000, 231, 1234, 121, 448};
    System.out.println(Arrays.toString(mergeSort.sort(nums)));
  }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值