We are going to implement merge sort recursively.
Steps:
If the array has more than one element, split it into two halves.
Recursively sort the two halves.
Merge the two sorted halves.
How merging works:
We have two sorted arrays (or two sorted parts of the same array, but for simplicity we'll use temporary arrays).
We compare the first elements of each array and take the smaller one, then move the pointer in that array.
Continue until one array is exhausted, then append the remaining elements of the other array.
However, note that in the recursive implementation we usually use a helper function for merging.
Let's write:
merge_sort(arr):
if length of arr <= 1:
return arr
code
mid = len(arr) // 2
left = merge_sort(arr[0:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
code
# Append the remaining elements
result.extend(left[i:])
result.extend(right[j:])
return result
But note: this implementation creates new lists for left and right and for the result.
This is not in-place and uses extra space.
However, the problem asks for a recursive implementation and to explain the merging process.
Let's write the code accordingly and then explain.
Alternatively, we can do an in-place merge sort, but that is more complex and not typically done in a simple recursive version.
We'll stick to the above.
However, note that the above uses slicing which creates new lists. We can also pass indices to avoid extra list creation, but for clarity we'll do as above.
Let me write the code accordingly.
Merge Sort Algorithm
Merge Sort is a divide-and-conquer sorting algorithm that works by:
Dividing the unsorted list into smaller sublists (until each contains 1 element)
Conquering by recursively sorting the sublists
Merging the sorted sublists back together to produce the final sorted list
Key Characteristics:
Time Complexity: O(n log n) in all cases (worst, average, best)
Space Complexity: O(n) (requires temporary arrays for merging)
Stable: Maintains relative order of equal elements
Not in-place: Requires additional memory for merging
Recursive Implementation (Python)
python
def merge_sort(arr):
"""Recursive merge sort implementation"""
# Base case: arrays with 0 or 1 element are already sorted
if len(arr) <= 1:
return arr
# 1. DIVIDE: Split array into two halves
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
# 2. CONQUER: Recursively sort both halves
left_sorted = merge_sort(left_half)
right_sorted = merge_sort(right_half)
# 3. MERGE: Combine the sorted halves
return merge(left_sorted, right_sorted)
def merge(left, right):
"""Merges two sorted arrays into one sorted array"""
result = [] # Temporary array to store merged result
i = j = 0 # Pointers for left and right arrays
# Compare elements from both arrays and add smaller to result
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
# Append remaining elements (only one of these will have leftovers)
result.extend(left[i:])
result.extend(right[j:])
return result
# Example usage
if __name__ == "__main__":
arr = [38, 27, 43, 3, 9, 82, 10]
print("Original:", arr)
sorted_arr = merge_sort(arr)
print("Sorted:", sorted_arr)
How the Merging Process Works
The merge function is where the actual sorting happens. Here's a step-by-step explanation:
Step 1: Setup
python
left = [27, 38] # Already sorted subarray
right = [3, 9, 10, 43, 82] # Already sorted subarray
result = []
i = 0 # Pointer for left array
j = 0 # Pointer for right array
Step 2: Compare & Append Process
We compare elements at current positions (i and j) and append the smaller one to result: