分治:
//分+合并
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);
}
}
//合并的方法
//int []temp作为中转
public void merge(int []arr,int left,int mid,int right,int []temp){
int i=left;
int j=mid+1;
int t=0; //指向temp的当前索引
// 1.先把左右两边的数组按照规则填充到temp,直到有一边处理完为止
while(i<=mid&&j<=right){
//若左边小于右边,左边进数组,并前进
if(arr[i]<=arr[j]){
temp[t]=arr[i];
i+=1;
t+=1;
}else{
temp[t]=arr[j];
j+=1;
t+=1;
}
}
// 2.把有剩余的数据的一边依次全部充到temp数组
while(i<=mid){ //说明左边剩余
temp[t]=arr[i];
t+=1;
i+=1;
}
while(j<=right){ //说明左边剩余
temp[t]=arr[j];
t+=1;
j+=1;
}
//3.将temp数组的元素复制到arr
t=0;
int tempLeft=left;
System.out.println("tempLeft="+tempLeft+" "+"right="+right);
while(tempLeft<=right){
//第一次合并,tempLeft是0,right是1
//第二次tempLeft是2,right是3 数组是0-3
//最后一次是0-7
arr[tempLeft]=temp[t];
t+=1;
tempLeft+=1;
}
}