本文主要加入了辅助数组,使得merge方法的空间复杂为O(n)。
import java.util.Arrays;
/*
* 改进merge方法的空间复杂度,通过一个辅助数组,使得空间复杂度为O(n)
* 1.把数组分为左右2个子数组(终止条件数组长度为1,不再分),分别进行mergeSort排序
* 2.有序的左右子数组,合并到辅助数组
* 3.从辅助数组中将修改了的数据复制会原数组
*
*/
public class MergeSort4 extends AbstractSort {
@Override
public void sort(int[] a) {
if (a == null || a.length <= 1) {
return;
}
// 辅助数组
int[] copy = Arrays.copyOf(a, a.length);
mergeSort(a, copy, 0, a.length - 1);
}
private void mergeSort(int[] a, int[] copy, int start, int end) {
// 元素大于2个才进行mergeSort
if (end > start) {
int mid = (end + start) >> 1;
mergeSort(a, copy, start, mid);
mergeSort(a, copy, mid + 1, end);
merge(a, copy, start, mid, mid + 1, end);
}
}
/*
* 合并数据
*/
private void merge(int[] a, int[] copy, final int start1, final int end1, final int start2, final int end2) {
int indexCopy = start1;
int index1 = start1, index2 = start2;
while (index1 <= end1 && index2 <= end2) {
if (a[index1] < a[index2]) {
copy[indexCopy++] = a[index1++];
} else {
copy[indexCopy++] = a[index2++];
}
}
while (index1 <= end1) {
copy[indexCopy++] = a[index1++];
}
while (index2 <= end2) {
copy[indexCopy++] = a[index2++];
}
//将修改了的部分放会原数组
for(int i=start1;i<=end2;i++) {
a[i]=copy[i];
}
}
}