简体   繁体   中英

Levels of recursion in merge sort

How do I determine how many levels of recursion are necessary for merge sort to sort a list of size 8?

I am looking for only the level of recursive calls, not the return steps.

will it be 4?

Because if I have a list: {18,16,13,14,11,12,15,17} I can sort it in 4 levels using recursion

{18,16,13,14,11,12,15,17}

one initial call, then a level of recursion for each time you need to divide the list in half before you get down to single-element lists.

{18,16,13,14} {11,12,15,17}
{18,16} {13,14} {11,12} {15,17}
{18} {16} {13} {14} {11} {12} {15} {17}

or log2(n) levels plus 1 = log2(8) + 1 = 4

You must define the terms level of recursion precisely: it refers conventionally to the depth of recursion, but does the first call count? In your example, you show 3 levels of recursion, but the depth of the call stack is 4 including the initial call with the full array.

Furthermore, there would be an extra level if the array size was just one greater than 8 , which your formula would fail to account for.

Here is a more accurate algorithm, counting the initial call:

  • if the length is 0 or 1, depth is 1
  • otherwise, depth is 2 + log2(length - 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM