AlgoTales · Roadmap

Merge sort

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Merge sort splits a list in halves again and again until each piece has one item, then merges pieces back together by always taking the smaller front item. It is steady and reliable, and it can sort data too big to fit in memory.

Practical use cases

  • Web app: Sorting a huge CSV export. A report must sort 50 lakh transactions that do not all fit in memory at once. The job sorts chunks, saves them, and then merges the sorted chunks together a little at a time. The export finishes without crashing the server on memory.
  • Web app: Combining two sorted lists. A job portal gets 200 sorted results from one database and 150 from another service. Instead of mixing them and sorting again, the code merges the two lists in one pass. The combined page appears in order and fast, with no second full sort.
  • System: Library sort routines. Many language libraries use a merge-based sort, such as Python and Java for objects, because it behaves predictably on any data and keeps equal items in their original order. Users appreciate that stability in tables, and it is why merge sort is also the usual choice for huge files on disk.

The story: Two Queues, One Window

At the railway ticket counter there was only one window, but two queues had formed, and, amazingly, each queue was already arranged by seat-request number: lowest at the front. The clerk, Raju's uncle, had to serve everybody in one overall order.

He did not need to ask anybody to re-sort. He simply looked at the two people at the front, called the one with the smaller number, and then looked at the two fronts again. Repeat. When one queue ran out, the rest of the other queue just followed. That quick joining of two sorted lines is called a merge.

Mira had a bigger idea. "What if the queues are not sorted?" Mrs. Sharma smiled: "Then split each queue in half again and again until every group is a single person. A single person is always sorted. Then merge them back, pair by pair, up the chain."

Split in halves, then merge back together: that is merge sort. It is steady and predictable: always about the same speed, no matter how jumbled the start.

How to spot this problem, and where you need it

You must sort a large amount of data reliably, possibly more than fits in memory, or combine several already sorted lists into one sorted list.

Signs you need it

  • The data is huge, comes from files or several sources, and loading everything at once strains memory.
  • You have two or more lists that are each sorted and you need one sorted result, such as combining pages of search results.
  • You need a stable sort that never slows down badly on awkward data, and equal items must keep their earlier order.

Where to use it in a project

  • Sorting and merging big exports, logs and database result sets in batch jobs.
  • Merging search results or feeds from multiple services into one ordered list.

The solution

Divide the list into two halves, sort each half the same way, and then merge. To merge two sorted halves, look at the front item of each, take the smaller, and move on. Keep going until both halves are used up. Because each level of splitting touches every item once, and the number of levels is small, the total work stays low even for millions of items.

Payoff: Before: sorting 50 lakh rows ran out of memory. After: sorted chunks merged in steady steps and the report finished in minutes.

Explain it like I am 8

Cut a messy pile of cards into two smaller piles, then keep cutting until each pile is a single card. Then zip two piles together by always taking the smaller top card. Zipping sorted piles is easy, and the zippers add up to a fully sorted deck.

How it works, step by step

  1. Divide: if the list has 0 or 1 items, it is already sorted. Otherwise cut it into a left half and a right half.
  2. Conquer: sort each half by calling the same function on it (recursion).
  3. Merge: keep a finger on the front of each sorted half. Copy the smaller front into a new list and move that finger.
  4. When one half runs out, copy the rest of the other half.
  5. Taking from the left on a tie (<=) keeps equal items in their original order, so merge sort is stable.

The code in four languages

PHP

<?php
// Merge sort: split in half, sort each half, merge the two sorted halves.
function mergeSort(array $a): array {
    if (count($a) <= 1) return $a;                 // one student is always sorted
    $mid = intdiv(count($a), 2);
    $left  = mergeSort(array_slice($a, 0, $mid));
    $right = mergeSort(array_slice($a, $mid));

    $out = [];
    $i = 0; $j = 0;
    while ($i < count($left) && $j < count($right)) {
        // compare only the two fronts; <= keeps equal items in original order
        if ($left[$i] <= $right[$j]) $out[] = $left[$i++];
        else                         $out[] = $right[$j++];
    }
    while ($i < count($left))  $out[] = $left[$i++];    // copy leftovers
    while ($j < count($right)) $out[] = $right[$j++];
    return $out;
}
echo implode(', ', mergeSort([6, 2, 7, 1, 4, 3]));      // 1, 2, 3, 4, 6, 7

JavaScript

// Merge sort: split in half, sort each half, merge the two sorted halves.
function mergeSort(a) {
  if (a.length <= 1) return a;                    // one student is always sorted
  const mid = Math.floor(a.length / 2);
  const left = mergeSort(a.slice(0, mid));
  const right = mergeSort(a.slice(mid));

  const out = [];
  let i = 0, j = 0;
  while (i < left.length && j < right.length) {
    // compare only the two fronts; <= keeps equal items in original order
    if (left[i] <= right[j]) out.push(left[i++]);
    else out.push(right[j++]);
  }
  while (i < left.length) out.push(left[i++]);    // copy leftovers
  while (j < right.length) out.push(right[j++]);
  return out;
}
console.log(mergeSort([6, 2, 7, 1, 4, 3]).join(', '));    // 1, 2, 3, 4, 6, 7

Java

import java.util.*;

public class Main {
    // Merge sort: split in half, sort each half, merge the two sorted halves.
    static int[] mergeSort(int[] a) {
        if (a.length <= 1) return a;                       // one student is always sorted
        int mid = a.length / 2;
        int[] left = mergeSort(Arrays.copyOfRange(a, 0, mid));
        int[] right = mergeSort(Arrays.copyOfRange(a, mid, a.length));

        int[] out = new int[a.length];
        int i = 0, j = 0, k = 0;
        while (i < left.length && j < right.length) {
            // compare only the two fronts; <= keeps equal items in original order
            if (left[i] <= right[j]) out[k++] = left[i++];
            else out[k++] = right[j++];
        }
        while (i < left.length) out[k++] = left[i++];      // copy leftovers
        while (j < right.length) out[k++] = right[j++];
        return out;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(mergeSort(new int[]{6, 2, 7, 1, 4, 3})));   // [1, 2, 3, 4, 6, 7]
    }
}

Go

package main

import "fmt"

// mergeSort: split in half, sort each half, merge the two sorted halves.
func mergeSort(a []int) []int {
	if len(a) <= 1 {
		return a // one student is always sorted
	}
	mid := len(a) / 2
	left := mergeSort(a[:mid])
	right := mergeSort(a[mid:])

	out := make([]int, 0, len(a))
	i, j := 0, 0
	for i < len(left) && j < len(right) {
		// compare only the two fronts; <= keeps equal items in original order
		if left[i] <= right[j] {
			out = append(out, left[i])
			i++
		} else {
			out = append(out, right[j])
			j++
		}
	}
	out = append(out, left[i:]...) // copy leftovers
	out = append(out, right[j:]...)
	return out
}

func main() {
	fmt.Println(mergeSort([]int{6, 2, 7, 1, 4, 3})) // [1 2 3 4 6 7]
}

Time: O(n log n) · Extra space: O(n). The list is halved about log n times, and each level of merging touches every item once. The price is the extra list for merging.

Watch out for

  • Forgetting the base case (length <= 1), which causes infinite recursion.
  • Forgetting to copy the leftover items after one half runs out, so items vanish.
  • Using < instead of <= when comparing fronts. It still sorts, but equal items can swap order (not stable).

Quick check

  1. What does the merge step need as input?
    • Two sorted lists
    • One unsorted list
    • A list of unique numbers only
  2. Merge sort on an already sorted list takes roughly...
    • O(n)
    • O(1)
    • The same O(n log n) as on any list
  3. What is merge sort's main drawback compared to insertion sort?
    • It needs extra memory for merging
    • It is slower on every list
    • It cannot sort numbers