Merge Sort

About

Merge Sort breaks a big sorting problem down into microscopic, easy-to-solve pieces using a recursive strategy.

  1. Divide: It keeps cutting the array in half until it is completely broken down into single-element subarrays (which are inherently sorted).

  2. Conquer: It zips those small pieces back together in pairs. When merging two sorted pieces, it compares their front-most elements, takes the smaller one, and builds a perfectly combined, sorted array, working its way all the way back up to the top.

![[mer.mp4]]

Complexities

Code Implementation

def merge_sort(arr):
    # Base case: A single element or empty array is already sorted
    if len(arr) <= 1:
        return arr
        
    # Find the middle point to split the array
    mid = len(arr) // 2
    
    # Recursively split and sort the left and right halves
    left_half = merge_sort(arr[:mid])
    right_half = merge_sort(arr[mid:])
    
    # Merge the sorted halves back together
    return merge(left_half, right_half)


def merge(left, right):
    sorted_arr = []
    i = j = 0  # Pointers for tracking indices in left and right lists
    
    # Compare elements from both lists and assemble them in order
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:  # The '<=' ensures stability
            sorted_arr.append(left[i])
            i += 1
        else:
            sorted_arr.append(right[j])
            j += 1
            
    # Gather any remaining elements left over from either array
    sorted_arr.extend(left[i:])
    sorted_arr.extend(right[j:])
    
    return sorted_arr

Key Takeaways

Powered by Forestry.md