自学记录
public class MergeSort {
public static void main(String[] args){
int[] b={4,4,1,2,-9,10,101,2,23,9,-40,13,14,5,-8,2,1};
mergeSort(b);
SortTest.show(b);
}
public static void mergeSort(int[] a){
int low,mid,high,step=1,len=a.length;
//step不能大于等于区间长度,只能小于;
while (step<len){
low=0;//从头开始找
// low +step-1+1<=length-1,保证high存在,若连长度为到mid为1的high值都越界了,就不执行循环,例如 (0,1),(2,3),4
while (low+step<len){
mid=low+step-1;
high=mid+step;//mid+1+step-1
if(high>len-1){ //high别越界了
high=len-1;
}
merge(a,low,mid,high);
low=high+1;
}
step*=2;//一步两,两步四个...
}
}
public static void merge(int[] arr, int low, int mid ,int high){
int i=low,j=mid+1,k=0;
int[] temp = new int[high-low+1];//临时矩阵;
while (i<=mid && j<=high){
if(arr[i]<=arr[j]){ //比较大小;
temp[k++]=arr[i++];
}
else{
temp[k++]=arr[j++];
}
}
while(i<=mid){
temp[k++]=arr[i++];//把剩下的补齐
}
while (j<=high){
temp[k++]=arr[j++];
}
for(i=low,k=0;i<=high;i++,k++){
arr[i]=temp[k];//写回去;
}
}
}