public static void execute(int[] arr){
// 当数组的长度小于等于1时就停止拆分
if(arr.length > 1){
/*左递归*/
int len = arr.length;
int leftLen = len/2;
int[] leftArr = new int[leftLen];
System.arraycopy(arr,0,leftArr,0,leftLen);
execute(leftArr);
/*右递归*/
int rigthLen = len - leftLen;
int[] rigthArr = new int[rigthLen];
System.arraycopy(arr,leftLen,rigthArr,0,rigthLen);
execute(rigthArr);
/*这里我们需要用个临时数组来存放排序后的数组,然后把临时数组的值copy到上一栈帧的局部变量表存放*/
int[] temp = merge(leftArr,rigthArr);
System.arraycopy(temp,0,arr,0,len);
}
}
/**
* @deprecated 合并
* @param left 左边的数组
* @param right 右边的数组
* @return arr
*/
public static int[] merge(int[] left,int[] right){
int leftLen = left.length;
int rightLen = right.length;
int[] arr = new int[leftLen+rightLen];
int i = 0,j = 0,index = 0;
while (i < leftLen && j < rightLen){
if(left[i] > right[j]){
arr[index++] = right[j++];
}else {
arr[index++] = left[i++];
}
}
while (i < leftLen){
arr[index++] = left[i++];
}
while (j < rightLen){
arr[index++] = right[j++];
}
return arr;
}
时间复杂度平均情况 | 时间复杂度最好情况 | 时间复杂度最坏情况 | 空间复杂度 | 稳定性 |
---|
O(nlogn) | O(nlogn) | O(nlogn) | O(n) | 稳定 |