public class Recursion {
@Resource
private Recursion recursion;
public void mergeSort(int[] arr) {//数据接口
int[] temp = new int[arr.length];
recursion.mergeSort(arr,0,arr.length-1,temp);
}
public void mergeSort(int[] arr, int left, int right, int[] temp) {
if (left < right) {
int mid = (left + right) / 2;
//向左递归分解
mergeSort(arr, left, mid, temp);
//向右递归分解
mergeSort(arr, mid + 1, right, temp);
merge(arr, left, mid, right, temp);
}
}
/**
* @param arr 初始数组
* @param left 左侧索引
* @param mid 中间索引
* @param right 右边索引
* @param temp 中转数组
*/
private void merge(int[] arr, int left, int mid, int right, int[] temp) {
int i = left;//左侧序列初始化索引
int j = mid+1;//右侧序列初始化索引
int t = 0;//temp 当前索引
while (i <= mid && j <=right){
if(arr[i] < arr[j]){
temp[t] = arr[i];
t++;
i++;
}else{
temp[t] = arr[j];
t++;
j++;
}
while (i <= mid){
temp[t] = arr[i];
t++;
i++;
}
while (j <= mid){
temp[t] = arr[j];
t++;
j++;
}
t= 0;
int tempLeft = left;
while (tempLeft <= right){
arr[tempLeft] = temp[t];
tempLeft += 1;
}
}
}
}