Merge sort, the recursion part

后端 未结 3 1759
猫巷女王i
猫巷女王i 2021-01-22 21:00

After studying the merge sort for a couple of days, I understand it conceptually, but there is one thing that I don\'t get.

What I get:

1.) It takes a list, for

相关标签:
3条回答
  • 2021-01-22 21:31

    If you are talking about odd numbered sub lists, then it is dependant on the implementation.

    It either puts the bigger sub list on the left every single time, or it puts it on the right every single time.

    0 讨论(0)
  • 2021-01-22 21:37

    Once the list only contains one element, each pair of leaves are sorted and joined. Then you can traverse through the list and find out where the next pair should be inserted. The recursion "knows" nothing about going back up the recursion tree, rather it is the act of sorting and joining that has this effect.

    0 讨论(0)
  • 2021-01-22 21:39

    The "recursion" does of course know nothing of that sort. It is the code that uses the recursion, which looks like this (a bit simplified):

    sort list = merge (sort left_half) (sort right_half)
        where
             (left_half, right_half) = split list
    

    Here you see that the "recursion" (i.e. the recursive invocations of sort) don't need to "know" anything. Their only job is to deliver a sorted list, array or whatever.

    To put it differently: If we have merge satisfying the following invariant:

    1. `merge`, given two sorted lists, will return a sorted list.
    

    then we can write mergesort easily like outlined above. What is left to do in sort is to handle the easy cases: empty list, singleton and list with two elements.

    0 讨论(0)
提交回复
热议问题