Understanding the Recursion of mergesort

后端 未结 9 2055
感动是毒
感动是毒 2020-12-13 07:01

Most of the mergesort implementations I see are similar to this. intro to algorithms book along with online implentations I search for. My recursion chops don\'t go much fur

9条回答
  •  余生分开走
    2020-12-13 07:37

    I know this is an old question but wanted to throw my thoughts of what helped me understand merge sort.

    There are two big parts to merge sort

    1. Splitting of the array into smaller chunks (dividing)
    2. Merging the array together (conquering)

    The role of the recurison is simply the dividing portion.

    I think what confuses most people is that they think there is a lot of logic in the splitting and determining what to split, but most of the actual logic of sorting happens on the merge. The recursion is simply there to divide and do the first half and then the second half is really just looping, copying things over.

    I see some answers that mention pivots but I would recommend not associating the word "pivot" with merge sort because that's an easy way to confuse merge sort with quicksort (which is heavily reliant on choosing a "pivot"). They are both "divide and conquer" algorithms. For merge sort the division always happens in the middle whereas for quicksort you can be clever with the division when choosing an optimal pivot.

提交回复
热议问题