Two recursive calls in a Merge Sort function confusion

前端 未结 9 1637
情书的邮戳
情书的邮戳 2021-02-19 13:37

I have been out of touch with Algorithms for a while and have start revising my concepts these days. To my surprise the last i remember of my recursions skill was that i was goo

9条回答
  •  旧巷少年郎
    2021-02-19 13:42

    Merge Sort uses a recursive algorithm to create a complete binary tree with a height of Log N, being N the number of nodes of that tree (this is why is so efficient). In the next image you can see step by step what is the flow of execution of this algorithm for your case, with the binary tree that is created (which I think is the best way to understand how it works):

    Binary tree that is generated using Merge Sort with an array of 8 positions

    What Merge Sort does is to split the array in halves recursively, going first to the lowest halves until we reach one unitary element, and then go and split the higher ones from the lowest element recently reached. This is why it calls itself two times per each previous call, in order to create a complete binary tree that stops when we reach one unit (with leaf nodes) and only merge when we have two (with parent nodes). In the following image you can see how your array is split recursively, step by step:

    Step by step division of an array of 8 elements using Merge Sort

提交回复
热议问题