1/29/2024
Merge Sort #2nd attempt
This is my second attempt solving Sort an Array problem using merge sort. Some lessons I learned from this attempt:
- Always remember to add a base case in a recursive function.
- The sorting actually happens in the second for loop of the merge function. In this for loop, each element is put back to array
a
in order. Even though the pre-condition of the merge is that the two sub-arrays are already sorted, when we reach the base case, two sub-arrays only contain 1 element each, which means we actually sort by comparing these two elements and then putting them back into the original array. - The second for loop in the merge function goes over all places of the portion that needs to be merged in the original array and considers which element among the two elements in aux and pointed by the two pointers that need to be in each place.