Skip to content

Merge Sort ​

Merge sort splits an array in half again and again until it can't be split any further, then sorts by merging the small pieces back together in order.

At a Glance ​

  • It is also called merge sort (합병 정렬) and is implemented with the divide and conquer approach.
  • Divide and conquer = solving a big problem by breaking it down into smaller problems.
  • As an analogy: sorting 100 shuffled exam sheets alone is hard, so you split them in two and hand half to a friend, and the friend splits their pile in half again and hands it off, and so on. A single sheet is already sorted, so after that all you have to do is take two sorted piles, compare the top sheets, and merge them into one pile.
  • It is classified as a fast sort and is often mentioned together with quick sort.
  • It is a comparison sort, which sorts by comparing values with each other.
  • Unlike quick sort, it is a stable sort. Elements with equal values keep their original order.
  • It needs a temporary array when merging, so it is not an in-place sort.

How It Works ​

The elements are split apart and then sorted while being merged back together. The way it splits is similar to quick sort.

  1. Split the array at the middle (mid) into a left half and a right half.
  2. Keep splitting until each piece has length 1. A piece of length 1 is already sorted.
  3. Compare the front elements of two sorted pieces and take the smaller value first to merge them into one (merge).
  4. Repeat merging until everything is one piece again.

Example array [6, 5, 3, 1, 8, 7, 2, 4]:

StepArray stateDescription
Start[6, 5, 3, 1, 8, 7, 2, 4]Before sorting
Split 1[6, 5, 3, 1] [8, 7, 2, 4]Split in half
Split 2[6, 5] [3, 1] [8, 7] [2, 4]Split in half again
Split 3[6] [5] [3] [1] [8] [7] [2] [4]Stop at length 1
Merge 1[5, 6] [1, 3] [7, 8] [2, 4]Compare and merge pairs
Merge 2[1, 3, 5, 6] [2, 4, 7, 8]Merge into groups of four
Merge 3[1, 2, 3, 4, 5, 6, 7, 8]Sorting complete

Here is a closer look at what merge does in the last merge step. Because the two pieces are each already sorted, you only need to compare their front elements in order.

ComparisonLeft [1, 3, 5, 6]Right [2, 4, 7, 8]Value added to result
1121
2322
3343
4544
5575
6676
End(empty)7, 8Append the remaining 7, 8 as is

Difference from Quick Sort ​

  • Quick sort: first sort around a pivot (partition) → split the range (quickSort)
  • Merge sort: first split the range as far as possible (mergeSort) → sort while merging (merge)

In other words, quick sort does its work "before splitting," while merge sort does its work "while merging after splitting." That is why the heart of merge sort is the merge() function.

In Pictures ​

The figure below shows [38, 27, 43, 3, 9, 82, 10] being sorted. The red arrows are the splitting steps, and the green arrows are the steps that sort while merging.

The split and merge process of merge sort

Image source: Wikimedia Commons (public domain)

If you watch the same process as an animation, you can see small pieces staying sorted while they are merged into bigger and bigger chunks.

Merge sort animation

Image source: Wikimedia Commons (CC BY-SA 3.0, Swfung8)

Python Code ​

The two functions from the original, mergeSort and merge, are ported directly to Python. left and right are the indexes of both ends of the range to sort (inclusive).

python
def merge_sort(array, left, right):
    # 1. Only split when there are 2 or more cells (1 cell is already sorted)
    if left < right:
        mid = (left + right) // 2
        # 2. Sort the left half and the right half separately
        merge_sort(array, left, mid)
        merge_sort(array, mid + 1, right)
        # 3. Merge the two sorted halves into one
        merge(array, left, mid, right)


def merge(array, left, mid, right):
    # 4. Copy the two ranges separately
    L = array[left:mid + 1]
    R = array[mid + 1:right + 1]

    i = j = 0
    k = left
    # 5. Compare the front elements of both ranges and fill in the smaller one first
    while i < len(L) and j < len(R):
        if L[i] <= R[j]:          # If equal, left goes first → stable sort
            array[k] = L[i]
            i += 1
        else:
            array[k] = R[j]
            j += 1
        k += 1

    # 6. When one side runs out first, append the rest as is
    while i < len(L):
        array[k] = L[i]
        i += 1
        k += 1
    while j < len(R):
        array[k] = R[j]
        j += 1
        k += 1


array = [230, 10, 60, 550, 40, 220, 20]
merge_sort(array, 0, len(array) - 1)
print(array)
# Output: [10, 20, 40, 60, 220, 230, 550]
  1. It only proceeds when left < right. If the range has only one element, there is nothing more to do.
  2. Using the middle mid as the boundary, it recursively sorts the left part [left, mid] and the right part [mid + 1, right].
  3. After both sides are sorted, they are combined with merge. The core of the sorting logic is this merge().
  4. The result has to be written back into the original array, so the two ranges are first copied into L and R. These copies are why extra memory is needed.
  5. It compares the front elements of L and R and puts the smaller value into array[k]. Because it uses <=, when values are equal the left one (the one that was originally earlier) goes in first, which makes it a stable sort.
  6. Once one side is used up, the values left on the other side are already sorted, so they are simply appended at the end.

Time and Space Complexity ​

CaseTime complexity
BestΩ(n log n)
AverageΘ(n log n)
WorstO(n log n)
  • Since the array is halved each time, there are log n levels of splitting, and the merge work at each level scans all n elements once, which is O(n). So no matter what the input looks like, it is always n log n. (See the time complexity article.)
  • Space complexity: for arrays, O(n) extra memory (the temporary arrays L and R used for merging) + O(log n) for the recursive call stack. For a linked list, you can merge by just relinking nodes, so no temporary array is needed.

Why It Works Well for Sorting Linked Lists ​

Merge sort works through sequential comparisons, so it is efficient when you need to sort a linked list.

What happens if you sort a linked list with quick sort?

  • Performance is poor.
  • Quick sort relies heavily on random access that jumps straight to a desired position, such as picking a good pivot (like the middle value) or swapping while moving pointers inward from both ends.

Linked lists are useful for insertion and deletion, but inefficient for access.

  • An array can be accessed directly by index, but a linked list has to be followed one node at a time starting from the Head.
  • Access cost: array O(1) vs linked list O(n)

So using quick sort, which accesses elements randomly, on a linked list creates a lot of overhead. Merge sort's merge, on the other hand, only looks at the front of the two lists and moves forward one step at a time, which fits linked lists well.

Using It in Mini Git ​

Below are notes from implementing sorting by hand in the Mini Git assignment.

No sorted() or list.sort()! Build it yourself. The recommendation is merge sort:

Idea: "Split in half, sort each half, then interleave the two chunks in order"

[38, 27, 43, 10]
   ├→ [38, 27] → [27, 38]
   └→ [43, 10] → [10, 43]
   merge → [10, 27, 38, 43]
python
def merge_sort(items, compare):
    """Merge sort that sorts items based on the compare function"""
    if len(items) <= 1:
        return items                       # 1 element is already sorted
    mid = len(items) // 2
    left = merge_sort(items[:mid], compare)   # sort the left half
    right = merge_sort(items[mid:], compare)  # sort the right half
    merged = []                            # merging the two chunks
    i = j = 0
    while i < len(left) and j < len(right):
        if compare(left[i], right[j]) <= 0:  # if left is smaller or equal
            merged.append(left[i]); i += 1
        else:
            merged.append(right[j]); j += 1
    return merged + left[i:] + right[j:]     # append whatever is left

Knowledge for explaining (assignment goal):

AlgorithmAverageWorstStable?
merge sortO(n log n)O(n log n)O (stable)
quick sortO(n log n)O(n²)X
bubble sortO(n²)O(n²)O

Stable sort = a sort in which elements with equal values keep their original order. Swapping the comparison rule: just change the key function, like compare = lambda a, b: a.timestamp - b.timestamp, and reuse the same merge_sort.

Summary ​

ConceptPlain-language summary
Merge sortKeep splitting in half, then merge two sorted piles by comparing their front elements
Divide and conquerBreak a big problem into small ones, solve them, then combine
Stable sortEqual values keep their original order
Sorting a linked listMerge sort fits well because it only needs to read from front to back
merge sortSplit in half, sort, then merge. Fast and stable

Source: Codyssey-B1/B5-2