Merge Sort in Python (original) (raw)

Last Updated : 30 Oct, 2025

Merge Sort is one of the most efficient and stable sorting algorithms based on the Divide and Conquer technique. It divides an input array into two halves, recursively sorts them, and then merges the two sorted halves using a function called merge().

The key function, merge(arr, l, m, r), assumes that both halves **arr[l..m] (left half) and **arr[m+1..r] (right half) are already sorted and merges them into one sorted array.

How Merge Sort Works

Here’s the step-by-step breakdown:

  1. **Divide: Recursively split the array into two halves until each subarray has only one element.
  2. **Conquer: Sort each subarray individually (they’re already sorted if they contain one element).
  3. **Merge: Combine the sorted subarrays into a single sorted array in the correct order.

Illustration of Merge Sort:

Let’s sort the array or list **[38, 27, 43, 10] using Merge Sort

Let’s look at the working of above example:

Divide:

Conquer:

Merge:

Therefore, the sorted list is [10, 27, 38, 43].

Python Implementation

Python `

def merge(arr, l, m, r): n1 = m - l + 1 n2 = r - m

L = [0] * n1
R = [0] * n2

for i in range(n1):
    L[i] = arr[l + i]
for j in range(n2):
    R[j] = arr[m + 1 + j]

i = j = 0
k = l

while i < n1 and j < n2:
    if L[i] <= R[j]:
        arr[k] = L[i]
        i += 1
    else:
        arr[k] = R[j]
        j += 1
    k += 1

while i < n1:
    arr[k] = L[i]
    i += 1
    k += 1
while j < n2:
    arr[k] = R[j]
    j += 1
    k += 1

def mergeSort(arr, l, r): if l < r: m = l + (r - l) // 2 mergeSort(arr, l, m) mergeSort(arr, m + 1, r) merge(arr, l, m, r)

arr = [12, 11, 13, 5, 6, 7] print("Given array is:", arr)

mergeSort(arr, 0, len(arr) - 1) print("Sorted array is:", arr)

`

Output

Given array is: [12, 11, 13, 5, 6, 7] Sorted array is: [5, 6, 7, 11, 12, 13]

**Explanation:

Divide:

Conquer:

Merge:

Advantages of Merge Sort

Disadvantages