Merge Sort

Merge Sort is a classic divide-and-conquer sorting algorithm. It divides the input array into two halves, recursively sorts each half, and then merges the sorted halves to produce the final sorted array.

Merge Sort is stable and guarantees O(n log n) time complexity in all cases. It is efficient for large datasets and is often used in external sorting (sorting data that doesn't fit in memory). However, it requires additional memory for the temporary arrays used during merging.

Merge Sort is not an in-place algorithm, but its predictable performance and stability make it a popular choice for many applications.

Time Complexity

CaseTime Complexity
BestO(n log n)
AverageO(n log n)
WorstO(n log n)

Code Examples

# Python - merge sort
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
    return arr