munch2024 / munch

2 stars 11 forks source link

Task 2.3 Understanding Complex Code: Merge Sort Program #98

Closed KeenParchment closed 8 months ago

KeenParchment commented 8 months ago

I have a Python code snippet that performs Merge Sort. This current program not only does not have any documentation of what the program is inputting, but, the program itself is complex to understand what is happening. In addition to any potential optimization that the code could have, and overall readability.

Goals for Understanding Complex Code:

  1. Documentation needed
  2. Any potential performance optimization
  3. Increase readability

Code Snippet:

def merge_sort(arr):

    if len(arr) > 1:
        mid = len(arr) // 2
        left_half = arr[:mid]
        right_half = arr[mid:]

        merge_sort(left_half)
        merge_sort(right_half)

        i = j = k = 0

        while i < len(left_half) and j < len(right_half):
            if left_half[i] < right_half[j]:
                arr[k] = left_half[i]
                i += 1
            else:
                arr[k] = right_half[j]
                j += 1
            k += 1

        while i < len(left_half):
            arr[k] = left_half[i]
            i += 1
            k += 1

        while j < len(right_half):
            arr[k] = right_half[j]
            j += 1
            k += 1

    return arr