LLY19960418
锁五龙
采纳率0%
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);
}
}

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

1条回答 默认 最新

相关推荐