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