I'll implement a merge sort algorithm using pure Python, without relying on any external libraries. I'll provide a clear, step-by-step implementation with comments to explain the process.
def merge_sort(arr):
# Base case: if the array has 1 or fewer elements, it's already sorted
if len(arr) <= 1:
return arr
# Divide the array into two halves
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
# Recursively sort both halves
left_half = merge_sort(left_half)
right_half = merge_sort(right_half)
# Merge the sorted halves
return merge(left_half, right_half)
def merge(left, right):
# Initialize result array and index trackers
result = []
left_index = 0
right_index = 0
# Compare and merge elements from both lists
while left_index < len(left) and right_index < len(right):
# If left element is smaller or equal, add it to result
if left[left_index] <= right[right_index]:
result.append(left[left_index])
left_index += 1
# Otherwise, add right element
else:
result.append(right[right_index])
right_index += 1
# Add remaining elements from left list (if any)
result.extend(left[left_index:])
# Add remaining elements from right list (if any)
result.extend(right[right_index:])
return result
# Example usage and testing
def main():
# Test with various input lists
test_cases = [
[38, 27, 43, 3, 9, 82, 10],
[5, 2, 9, 1, 7, 6, 3],
[],
[1],
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
]
for case in test_cases:
print(f"Original array: {case}")
sorted_array = merge_sort(case)
print(f"Sorted array: {sorted_array}")
print()
# Run the main function
if __name__ == "__main__":
main()
This implementation of merge sort has several key characteristics:
Key Features
-
Divide and Conquer Strategy:
- The algorithm recursively divides the array into smaller subarrays
- Sorts these subarrays
- Merges them back together
-
Time Complexity:
- O(n log n) in all cases (best, average, worst)
- Stable sorting algorithm
-
Space Complexity:
- O(n) additional space for merging
How It Works
-
merge_sort() function:
- Recursively splits the array
- Calls itself on left and right halves
- Base case is when array has 1 or fewer elements
-
merge() function:
- Compares elements from two sorted lists
- Builds a new sorted list by selecting smaller elements
- Handles remaining elements after one list is exhausted
Advantages
- Predictable performance
- Stable sorting (maintains relative order of equal elements)
- Works well for linked lists and large datasets
Potential Improvements
- For very small arrays, you might want to use insertion sort
- Can be optimized for in-place sorting to reduce space complexity
When you run this script, it will demonstrate merge sort on various test cases, showing the original and sorted arrays.