[REPOST]递归函数如何在合并排序中起作用? [英] [REPOST] How recursive function works in merge sort ?

查看:64
本文介绍了[REPOST]递归函数如何在合并排序中起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

void partition(int arr[],int low,int high){

    int mid;

    if(low<high){
        mid=(low+high)/2;
        partition(arr,low,mid);
        partition(arr,mid+1,high); // How does the recursion work here?
        mergeSort(arr,low,mid,high);
    }
}



谢谢,mahbub


Thanks, mahbub

推荐答案

它的工作原理就像递归一样功能呢。在这种特殊情况下,分区在数组的连续半范围内调用自身(直到范围退化为单个项目,这是其递归的停止条件)。我建议你用纸和铅笔模拟函数调用,使用短数组作为输入。
Well it works like recursive functions do. In this particular case partition call itself on successive half-ranges of the array (until the range degenerates to a single item, this is the stop condition of its recursion). I suggest you to simulate the function calls with paper and pencil using a short array as input.


亲爱的朋友:



递归merge_sort的工作原理如下:

1-数组A [](长度为n)------> 2数组:数组a1 [](用lengs n / 2)

数组a2 [](长度为n / 2)



数组A [](长度为n):低----中----高



a1 [](长度为n / 2):低 - --mid

a2 [](长度为n / 2):mid + 1 ---- high







2 - 然后对每个数组进行排序(a1 []和a2 [])

a1 []:低---- mid

a2 []:mid + 1 ---- high



3-then merger(join)2排序数组(a1 []&a2 [] )直到我们获得1个排序数组(A []​​)

并且在每个步骤中:



1- mid =(低+高)/ 2;找到阵列的中心



2-分区(arr,低,中);排序数组A []的下半部分---- mid



3-分区(arr,mid + 1,high);排序数组的上半部分A [] mid + 1 ---- high



4- mergeSort(arr,low,mid,high);合并两个分类的部分





好​​luk
Dear Friend:

recursive merge_sort works as the following steps:
1- array A[] (with length n) ------> 2 array : array a1[] (with lengs n/2)
array a2[] (with length n/2)

array A[] (with length n): low----mid----high

a1[] (with length n/2) : low----mid
a2[] (with length n/2) : mid+1---- high



2-then sort each of arrays(a1[] & a2[])
a1[] : low----mid
a2[] : mid+1---- high

3-then merger(join) 2 sorted array(a1[] & a2[]) until we obtain 1 sorted array (A[])
and in each of steps :

1- mid=(low+high)/2; finding the center of array

2- partition(arr,low,mid); sorting the lower half of array A[] low----mid

3- partition(arr,mid+1,high); sorting the upper half of array A[] mid+1----high

4- mergeSort(arr,low,mid,high); merging two sorted parts


Good luk


这篇关于[REPOST]递归函数如何在合并排序中起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆