Implementing merge sort in Python is straightforward. Merge sort is a divide-and-conquer algorithm that divides the input array into two halves, recursively sorts each half, and then merges the sorted halves back together. It's efficient with a time complexity of O(n log n) and is stable.
Here's a step-by-step explanation and the Python implementation:
Steps of Merge Sort:
- Divide: If the array has more than one element, split it into two halves.
- Conquer: Recursively apply merge sort to each half.
- Combine: Merge the two sorted halves into a single sorted array.
Python Implementation:
Below is a complete, self-contained implementation of merge sort in Python. I'll include comments to explain each part.
def merge_sort(arr):
# Base case: If the array has 1 or 0 elements, it's already sorted
if len(arr) > 1:
mid = len(arr) // 2 # Find the middle point
# Divide the array into two halves
left_half = arr[:mid] # Left half
right_half = arr[mid:] # Right half
# Recursively sort the two halves
merge_sort(left_half)
merge_sort(right_half)
# Merge the sorted halves
i = j = k = 0 # Initialize indices
# Copy data to temp arrays (we'll merge back into arr)
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 # Move to the next position in arr
# If there are remaining elements in left_half
while i < len(left_half):
arr[k] = left_half[i]
i += 1
k += 1
# If there are remaining elements in right_half
while j < len(right_half):
arr[k] = right_half[j]
j += 1
k += 1
return arr # Return the sorted array
# Example usage
if __name__ == "__main__":
unsorted_array = [38, 27, 43, 3, 9, 82, 10]
print("Unsorted array:", unsorted_array)
sorted_array = merge_sort(unsorted_array.copy()) # Use copy to avoid modifying the original
print("Sorted array:", sorted_array)
Explanation of the Code:
- merge_sort function: This is the main function. It takes an array as input and recursively divides it until the base case is reached (array of length 0 or 1).
- Splitting the array: We use slicing (
arr[:mid] and arr[mid:]) to create the left and right halves.
- Merging: The merging happens in-place in the original array. We compare elements from the left and right halves and place them back into the original array in sorted order.
- Edge cases: The function handles empty arrays or arrays with a single element naturally, as the base case returns immediately.
Example Output:
If you run the code, you'll get:
Unsorted array: [38, 27, 43, 3, 9, 82, 10]
Sorted array: [3, 9, 10, 27, 38, 43, 82]
Additional Tips:
- Time Complexity: O(n log n) on average and worst case, where n is the number of elements.
- Space Complexity: O(n) due to the recursive calls and temporary space used for merging (though this implementation merges in-place to minimize extra space).
- Why use a copy in the example?: The function modifies the input array in-place. If you want to keep the original array unchanged, pass a copy (as shown).
- Improvements: If you're concerned about space, you could modify it to use a temporary array for merging, but this version is simple and effective for most use cases.
If you have any questions or want to modify this for a specific scenario (e.g., sorting in descending order), let me know!