时间复杂度:
O(n log n)
算法稳定性:
稳定
原理:
将两个有序数组归并为一个有序数组。(元素数量为 1 时也是有序数组哦)
步骤:
整个排序过程中有一个原数组 S ,有一个临时数组 T。分为两个步骤分割和归并。
1:将数组递归的从中间分割为两个子序列,直到不可在分(即子序列元素数量小于 1 )。然后利用 T 对两个子序列进行归并, 在将 T 中数据复制到 S。
2:退出递归得到结果。
没有图!
注:本系列算法是用于记录自己学习算法阶段对每个算法的自己理解。
@Override
public int[] sort(int[] source) {
int[] temp = new int[source.length];
return limit(source, temp, 0, source.length - 1);
}
public int[] limit(int[] source, int[] temp, int l, int r){
if (r - l < 1){
return source;
}
limit(source, temp, l, (l + r)/2);
limit(source, temp, (l + r)/2 + 1, r);
return merge(source, temp, l, (l + r)/2, r);
}
public int[] merge(int[] source,int[] temp, int l, int le, int r){
int rs = le + 1;
int index = l;
int start = l;
while (l <= le && rs <= r){
if (source[l] < source[rs]){
temp[index++] = source[l++];
} else {
temp[index++] = source[rs++];
}
}
while (l <= le){
temp[index++] = source[l++];
}
while (rs <= r){
temp[index++] = source[rs++];
}
return arrCopy(source, start, r, temp);
}
public static int[] arrCopy(int[] source, int l, int r, int[] temp){
for (int j = l; j <= r; j++){
source[j] = temp[j];
}
return source;
}