Merge sort, the recursion part

后端 未结 3 1913
猫巷女王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: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.

提交回复
热议问题