create a merge sort algorithm in python

Merge Sort is a divide-and-conquer algorithm that recursively divides the input array in half, sorts each half, and then merges the two halves back together in sorted order.

Here's the Python code for implementing Merge Sort:

main.py
def merge_sort(arr):
    if len(arr) > 1:
        mid = len(arr) // 2
        left_half = arr[:mid]
        right_half = arr[mid:]

        # Recursively sort both halves
        merge_sort(left_half)
        merge_sort(right_half)

        # Merge the sorted halves into a sorted whole
        left_idx = right_idx = sorted_idx = 0
        while left_idx < len(left_half) and right_idx < len(right_half):
            if left_half[left_idx] <= right_half[right_idx]:
                arr[sorted_idx] = left_half[left_idx]
                left_idx += 1
            else:
                arr[sorted_idx] = right_half[right_idx]
                right_idx += 1
            sorted_idx += 1

        # Copy remaining elements to array
        while left_idx < len(left_half):
            arr[sorted_idx] = left_half[left_idx]
            left_idx += 1
            sorted_idx += 1

        while right_idx < len(right_half):
            arr[sorted_idx] = right_half[right_idx]
            right_idx += 1
            sorted_idx += 1

1025 chars
33 lines

To use this function to sort an array, simply call merge_sort(your_array). The original array will be sorted in-place.

gistlibby LogSnag