###### 锁五龙

2017-07-08 00:53 阅读 2.5k

# 归并排序递归调用的流程理解

`````` static void mergearray(int[] a , int first , int mid , int last , int temp[]){
System.out.println(first+"-"+ mid +"-"+last);
int i = first , j = mid+1;
int m = mid , n = last;
int k = 0 ;

while(i<=m && j <= n){
if(a[i] <= a[j]){
temp[k++] = a[i++];
}else{
temp[k++] = a[j++];
}
}

while(i <= m){
temp[k++] = a[i++];
}

while(j <= n ){
temp[k++] = a[j++];
}

for( i = 0 ; i < k ; i++){
a[first+ i] = temp[i];
}
}
static int count = 0;
static void mergesort(int a[] , int first , int last , int temp[]){
if(first < last){
System.out.println( first + " - " + last);
int mid = (first + last) / 2;
mergesort(a, first, mid, temp);
mergesort(a, mid+1, last, temp);
mergearray(a, first, mid, last, temp);
}
}

public static void main(String[] args) {

int[] arr = {10,4,6,3,8,2,5,7};
int[] temp = new int[arr.length];
mergesort(arr, 0, arr.length-1, temp);
for (int i : temp) {
System.out.println(i);
}
}
``````

static void mergesort(int a[] , int first , int last , int temp[]){
if(first < last){
System.out.println( first + " - " + last);
int mid = (first + last) / 2;
mergesort(a, first, mid, temp);
mergesort(a, mid+1, last, temp);
mergearray(a, first, mid, last, temp);
}
}

• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享