Auxiliary space merge sort

mail@pastecode.io avatar
unknown
python
a year ago
1.7 kB
4
Indexable
Never
def merge_sort(arr):
    if len(arr) > 1:
        mid = len(arr) // 2  # Find the middle of the array
        left_half = arr[:mid]  # Split the array into two halves
        right_half = arr[mid:]

        merge_sort(left_half)  # Recursively sort the left half
        merge_sort(right_half)  # Recursively sort the right half

        i = j = k = 0

        # Copy data to temporary arrays left_half[] and right_half[]
        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

        # Check if any element was left
        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

def merge_and_sort(arr1, arr2):
    aux_size = min(len(arr1), len(arr2))
    aux_array = arr1[:aux_size] + arr2[:aux_size]
    
    # Sort the auxiliary array using merge sort
    merge_sort(aux_array)
    
    merged_array = aux_array + arr1[aux_size:] + arr2[aux_size:]
    
    return merged_array

# Test Case 1
arr1 = []
arr2 = [3, 7, 9]
result = merge_and_sort(arr1, arr2)
print(result)

# Test Case 2
arr1 = [2, 7, 9]
arr2 = [1]
result = merge_and_sort(arr1, arr2)
print(result)

# Test Case 4
arr1 = [1, 3, 5, 5, 15, 18, 21]
arr2 = [5, 5, 6, 8, 10, 12, 16, 17, 17, 20, 25, 28]
result = merge_and_sort(arr1, arr2)
print(result)

# Test Case 3
arr1 = [1, 7, 10, 15]
arr2 = [3, 8, 12, 18]
result = merge_and_sort(arr1, arr2)
print(result)