Merge sort is a popular sorting algorithm that uses a divide-and-conquer approach. It divides the input array into two halves, sorts them, and then merges them back together. This algorithm has a time complexity of O(n log n) in all cases (worst, average, and best).
Basic Steps
- Divide: Split the array into two halves.
- Conquer: Recursively sort both halves.
- Combine: Merge the two sorted halves into one.
Example
Here's a simple implementation of merge sort in Python:
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
# Example usage
arr = [38, 27, 43, 3, 9, 82, 10]
merge_sort(arr)
print(arr)
More Information
For more detailed information on merge sort, you can read our comprehensive guide on Sorting Algorithms.
Merge Sort Visualization