Scrivio Interview library
Sorting and intervalsSorting and searchingReported 15 times · 16 min read · updated 15 November 2026

Explain merge sort and write a complete working implementation.

1What merge sort does, told as a pile of exam papers

Imagine a teacher with a pile of exam papers that must be put in order of roll number. Sorting a big pile alone is tiring, so she splits it in half and hands each half to a helper. Each helper does the same, splitting and handing on, until somebody is holding a single paper, which is already in order because there is nothing to compare it with. Then the work flows back up. Each person who receives two sorted piles combines them into one sorted pile, by looking only at the top paper of each and taking the smaller one.

That is merge sort, and the question asks us to explain it and write a complete version. To sort means to arrange numbers from smallest to largest. Merge sort splits the array into two halves, sorts each half the same way, and then merges, which means combining two sorted lists into one sorted list. The whole method is the teacher and her helpers, written as a method that calls itself.

We will keep one example. The array is [38, 27, 43, 3, 9, 82, 10], seven numbers, and the answer is [3, 9, 10, 27, 38, 43, 82]. The picture shows both.

PictureThe example before and after sorting

Top row: the array we are given. Bottom row: the same seven numbers in increasing order.

  1. 382743398210391027384382
    n
    7
    smallest
    3
    largest
    82

    1The top row is [38, 27, 43, 3, 9, 82, 10]. Merge sort must turn it into the bottom row, [3, 9, 10, 27, 38, 43, 82].

What to assume

Do we sort the given array in place, so the caller's array ends up sorted?
We assume yes.
Must the sort be stable, which means that equal values keep the order they had before sorting?
We assume yes, because it matters as soon as we sort records by one field. And the input may be millions of numbers long, so a sort that takes n squared steps is not good enough.

If sorting algorithms feel like a lot to remember, here is some comfort. Merge sort has only two ideas in it. One is that a single element is already sorted. The other is the merge. Everything else is the splitting, which is just finding the middle. Once the merge makes sense, the rest follows almost by itself.

Because the question names the algorithm, the real test is whether our version is complete and correct. So a careful candidate asks a few things first. Do we sort the given array in place, so the caller's array ends up sorted? We assume yes. Must the sort be stable, which means that equal values keep the order they had before sorting? We assume yes, because it matters as soon as we sort records by one field. And the input may be millions of numbers long, so a sort that takes n squared steps is not good enough.

2How to recognise a divide and conquer sort

When beginners are asked to sort, they usually think of the methods they can do by hand, such as finding the smallest card and moving it to the front, again and again. Those work, but each pass handles only one element. The question here asks for something different: a method whose cost grows much more slowly as the input grows.

Let us take the clues one at a time. The first clue is the name merge sort itself, and the word merge in it. Merging two sorted lists is easy and fast, because at every step only the two front elements can be the smallest. So if we could somehow get two sorted halves, one cheap pass would finish the job.

The second clue is how we get those sorted halves. Each half is itself a smaller sorting problem of exactly the same kind. A problem that can be split into smaller copies of itself, solved separately, and then combined, is the classic shape of divide and conquer. The method keeps splitting until the pieces are so small, single elements, that they need no work at all.

This question sits in the sorting and intervals pattern, the family of problems where putting data in order is either the answer or the first step that makes the answer easy. Merge sort is its standard example of divide and conquer. The general rule to carry to new problems is this. When the answers for two halves can be combined in one linear pass, splitting in half and recursing gives a total cost of about n log n.

Some sorts look similar but behave differently. Quicksort also divides and conquers, but it does its work before recursing, by splitting around a chosen value, while merge sort does its work after, by merging. Quicksort sorts in place with little extra memory, but a bad choice of that value can make it take n squared steps, and it is not stable. Heap sort is always n log n and in place, but it is not stable either. Merge sort is the choice when we need a guaranteed bound and stability.

3The honest first attempt, insertion sort

The honest first attempt, our brute force, is a sort most of us could write without notes, insertion sort. It is how many people sort a hand of cards. We keep a sorted part at the front of the array and take the next element, shifting larger elements one place right until we find where it belongs, and dropping it into the gap.

Java
// Brute force: insertion sort grows a sorted prefix one element at a time.
static void insertionSort(int[] a) {
for (int i = 1; i < a.length; i++) {
int value = a[i];
int j = i - 1;
while (j >= 0 && a[j] > value) {
a[j + 1] = a[j]; // shift larger elements one step right
j--;
}
a[j + 1] = value; // drop the value into the gap
}
}

Let us run it on the example and count. Inserting 27 shifts 38 once. Inserting 43 shifts nothing. Inserting 3 shifts 43, 38 and 27, three shifts. Inserting 9 shifts three more, inserting 82 shifts none, and inserting 10 shifts 82, 43, 38 and 27, four shifts. That is 11 shifts and 15 comparisons for seven numbers. It is correct, stable and sorts in place, and for tiny or nearly sorted arrays it is genuinely fast.

But look at the worst case, an array in reverse order. Then the element at position i shifts past all i elements before it, so the total is 1 + 2 + ... + (n - 1), about n x n / 2 shifts. The time is O(n^2), read as order n squared, and for a million numbers that is around five hundred billion shifts. The space is O(1).

Where is the waste? Each new element is compared with the sorted part one element at a time, moving one step per comparison. What we learn from one comparison helps only with one neighbour. Merge sort does better by combining whole sorted blocks at once, so each comparison places one element in its final order within the block.

4Building merge sort from the merge outward

Let us start from the step that does the real work, the merge, exactly as the teacher's helpers do it with two sorted piles. Put a finger at the front of each sorted list. Compare the two front elements, copy the smaller one to the output, and move that finger one step. When one list runs out, copy the rest of the other. Every comparison places one element, so merging lists of total length n takes about n steps.

Here is the merge that finishes our example. By the time it runs, the left half has become [3, 27, 38, 43] and the right half [9, 10, 82], each sorted by earlier merges. The picture shows the two halves side by side in a scratch array, with i marking the front of the left half and j the front of the right half.

Step throughMerging [3, 27, 38, 43] with [9, 10, 82]

The scratch array holds both sorted halves. i is the front of the left half and j the front of the right half. Done cells have been copied to the output.

  1. 3027138243394105826ij
    output
    []

    1The halves are copied into the scratch array. i starts at index 0 and j at index 4, the first element of each half.

  2. 3027138243394105826ij
    output
    [3]

    2We compare 3 with 9. 3 is not bigger, so we take 3 from the left and move i to 27.

  3. 3027138243394105826ij
    output
    [3, 9]

    3Now 9 is smaller than 27, so we take 9 from the right and move j to 10.

  4. 3027138243394105826ij
    output
    [3, 9, 10]

    410 is smaller than 27, so we take 10 from the right as well, and j moves to 82.

  5. 3027138243394105826ij
    output
    [3, 9, 10, 27]

    527 is smaller than 82, so we take 27 from the left and move i to 38.

  6. 3027138243394105826ij
    output
    [3, 9, 10, 27, 38]

    638 is smaller than 82, so we take 38 and move i to 43.

  7. 3027138243394105826j
    output
    [3, 9, 10, 27, 38, 43]

    743 is smaller than 82, so we take 43. i moves past the end of the left half, which is now used up.

  8. 3027138243394105826
    output
    [3, 9, 10, 27, 38, 43, 82]

    8With the left half used up, the remaining 82 is copied without any comparison, and the merge is finished.

Seven elements were placed with six comparisons, because the last one needed none. That is what we mean by a linear merge: the work is about the number of elements, no more.

A beginner usually asks the next question here. The merge needs two sorted halves, but where do they come from? From the same method, applied to each half. And each of those halves is split again, until we reach pieces of a single element. A single element is always sorted, so the splitting stops there. That stopping point is called the base case. The method calls itself on smaller and smaller pieces, which is called recursion, and then every merge on the way back up combines two sorted pieces into a bigger sorted piece.

Why is this correct? Think of it in sizes. Pieces of size one are sorted, as we said. If the method sorts every piece smaller than some size correctly, then for a piece of that size it sorts both halves correctly, and merging two sorted halves gives a sorted whole. So it is correct for every size, building up from one.

There is one more decision, and it is where stability comes from. When the two front elements are equal, which one do we take? We take the one from the left half. The left half came first in the original array, so equal values keep their original order. Taking the right one would still sort the numbers, but it would quietly lose stability.

5Watching every merge on the example

Now let us watch the whole sort on our example. The method first splits all the way down on the left, merges back up the left half, and only then works on the right half. The picture shows the array after each of the six merges. lo and hi mark the range the merge has just combined.

Step throughMerge sort on [38, 27, 43, 3, 9, 82, 10], merge by merge

Each frame is the array after one merge. The marked cells are the range that merge combined, lo to hi.

  1. 3802714323394825106lohi
    merges done
    0

    1We start with the unsorted array. The first call splits 0 to 6 into 0 to 3 and 4 to 6, then keeps splitting the left side down to single elements.

  2. 2703814323394825106lohi
    merges done
    1
    left
    [38]
    right
    [27]

    2Merge 1 combines [38] and [27] into [27, 38], at indexes 0 and 1.

  3. 2703813243394825106lohi
    merges done
    2
    left
    [43]
    right
    [3]

    3Merge 2 combines [43] and [3] into [3, 43], at indexes 2 and 3.

  4. 3027138243394825106lohi
    merges done
    3
    left
    [27, 38]
    right
    [3, 43]

    4Merge 3 combines [27, 38] and [3, 43] into [3, 27, 38, 43]. The whole left half is now sorted.

  5. 3027138243394825106lohi
    merges done
    4
    left
    [9]
    right
    [82]

    5The right half splits into 4 to 5 and 6. Merge 4 combines [9] and [82] into [9, 82], which happens to change nothing.

  6. 3027138243394105826lohi
    merges done
    5
    left
    [9, 82]
    right
    [10]

    6Merge 5 combines [9, 82] and [10] into [9, 10, 82]. The right half is now sorted too.

  7. 3091102273384435826lohi
    merges done
    6
    result
    [3, 9, 10, 27, 38, 43, 82]

    7Merge 6 combines [3, 27, 38, 43] and [9, 10, 82], the merge we watched step by step, and the whole array is sorted.

Let us read a few frames back. The first three merges all happen inside the left half, because the recursion finishes the left side completely before it starts the right side. That surprises beginners, who often expect the splitting to happen level by level across the whole array. It does not. It goes deep on the left first, the way a helper finishes their own pile before passing it back.

Merge 4 changed nothing, because 9 and 82 were already in order. Merge sort does not notice that and does the merge anyway. And count the merges: seven elements needed six merges, one fewer than the number of elements, because every merge turns two pieces into one, and we start with seven pieces and end with one.

6The complete Java program

Here is the complete program. The public method mergeSort creates one scratch array, called buffer, and starts the recursion. sort splits a range and recurses, and merge combines two sorted neighbouring ranges. main sorts the example, an array with duplicates and negative numbers, an empty array and a single element.

Java
import java.util.Arrays;
public class MergeSort {
// Sorts a in place: O(n log n) time, O(n) extra space, stable.
static void mergeSort(int[] a) {
if (a.length < 2) return;
int[] buffer = new int[a.length]; // one scratch array, reused by every merge
sort(a, buffer, 0, a.length - 1);
}
private static void sort(int[] a, int[] buffer, int lo, int hi) {
if (lo >= hi) return; // zero or one element: already sorted
int mid = lo + (hi - lo) / 2;
sort(a, buffer, lo, mid); // sort the left half
sort(a, buffer, mid + 1, hi); // sort the right half
merge(a, buffer, lo, mid, hi); // combine two sorted halves
}
private static void merge(int[] a, int[] buffer, int lo, int mid, int hi) {
for (int k = lo; k <= hi; k++) buffer[k] = a[k];
int i = lo, j = mid + 1;
for (int k = lo; k <= hi; k++) {
if (i > mid) a[k] = buffer[j++]; // left half used up
else if (j > hi) a[k] = buffer[i++]; // right half used up
else if (buffer[j] < buffer[i]) a[k] = buffer[j++];
else a[k] = buffer[i++]; // ties take the left: stable
}
}
public static void main(String[] args) {
int[] a = {38, 27, 43, 3, 9, 82, 10};
mergeSort(a);
System.out.println(Arrays.toString(a)); // [3, 9, 10, 27, 38, 43, 82]
int[] b = {5, -1, 5, 0, -1};
mergeSort(b);
System.out.println(Arrays.toString(b)); // [-1, -1, 0, 5, 5]
int[] c = {};
mergeSort(c);
System.out.println(Arrays.toString(c)); // []
int[] d = {42};
mergeSort(d);
System.out.println(Arrays.toString(d)); // [42]
}
}

Let us read it in the order it runs. mergeSort returns at once for arrays shorter than two, since they are already sorted. Otherwise it creates buffer, the same length as the array, once and only once, and calls sort on the whole range, 0 to a.length - 1.

sort first checks the base case. If lo >= hi the range holds at most one element, so there is nothing to do. Otherwise it finds the middle with lo + (hi - lo) / 2. This looks roundabout next to (lo + hi) / 2, but for very large arrays lo + hi can pass the int limit and wrap around to a negative number, while hi - lo never does. Then it sorts the left half, sorts the right half, and merges them, the same three steps as the teacher.

merge first copies the range lo to hi into buffer, so that we can write the result back into a without overwriting values we still need. Then i starts at the left half's front, lo, and j at the right half's front, mid + 1. The loop fills a[k] for every k from lo to hi. If the left half is used up, we take from the right. If the right half is used up, we take from the left. Otherwise we take the right element only if it is strictly smaller, and on a tie we take the left one, which keeps the sort stable.

The beginner's mistake to avoid here is creating new arrays inside every call, for example copying each half into fresh arrays before merging. It works, but it creates garbage of about n log n elements in total. One shared buffer, created once, does the same job with n extra elements. The second common slip is writing buffer[j] <= buffer[i] in the merge, which sorts correctly but loses stability.

The program prints [3, 9, 10, 27, 38, 43, 82] for the example, [-1, -1, 0, 5, 5] for the array with duplicates and negatives, [] for the empty array and [42] for the single element.

7How much it costs, and why it is n log n

Let us count on the example first. The splitting made three levels of merges. On the lowest level merges 1, 2 and 4 touched six elements, on the middle level merges 3 and 5 touched seven, and the final merge touched seven. Each level touches at most n elements, and the number of levels is how many times we can halve n before reaching one, which is about log2 n, three for seven elements. So the time is about n x log2 n, written O(n log n).

The picture of the splitting below makes the levels visible. Every row of the tree is one level, and on each level the merges together handle each element once.

PictureHow the array splits into ranges

Each node is a range of indexes that one call of sort handles. Leaves are single elements, already sorted, and the merges climb back up the tree.

  1. 0-60-34-60-12-34-56012345
    merge levels
    3
    per level
    at most 7 elements
    merges
    6

    1The range 0-6 splits into 0-3 and 4-6, and so on down to single elements. There are about log2 n levels, and each level merges at most n elements.

Unlike quicksort, merge sort costs O(n log n) on every input, sorted, reversed or random, because the split is always at the middle and never depends on the values. For a million numbers that is about twenty million steps, against five hundred billion for insertion sort in its worst case.

The extra space is O(n) for the buffer, plus the recursion, which keeps one waiting call per level, about log n of them, so O(log n) for the call stack. That O(n) buffer is the price merge sort pays for its guarantee and its stability.

8Comparing sorts, and the cases at the edges

The table puts merge sort beside the sorts it is most often compared with, so you can say in one breath why you would choose it.

Comparing the approaches
AlgorithmWorst-case timeExtra spaceStable?
Insertion sort (brute force)O(n^2)O(1)yes
QuicksortO(n^2), O(n log n) on averageO(log n)no
Heap sortO(n log n)O(1)no
Merge sortO(n log n)O(n)yes

Now the edge cases. Arrays of length 0 or 1 return at the first line of mergeSort. Duplicates keep their original order because ties take the left element, and negative numbers need no special handling, since the comparisons work for any int. Real libraries add one refinement: for very small ranges they switch to insertion sort, which is faster on a handful of elements, and Java's own sort for objects, TimSort, is a merge sort that also notices runs that are already in order.

9Follow-up questions

Why is merge sort a good choice for linked lists?

A linked list cannot jump to its middle element, which hurts quicksort and heap sort, but merge sort only needs two things. It needs to split the list, which fast and slow pointers do by walking one reference two steps for every one step of the other, and it needs to merge two sorted lists, which is done by relinking nodes. Relinking needs no buffer, so merge sort sorts a linked list in O(n log n) time with only the recursion as extra space.

Can merge sort be written without recursion?

Yes, from the bottom up. We treat each element as a sorted block of size 1, merge neighbouring blocks into blocks of size 2, then 4, then 8, doubling the size each pass until one block covers the whole array. It uses the same merge and the same buffer, keeps the O(n log n) time, and needs no call stack. The same idea sorts data too large for memory, by merging sorted runs stored on disk.

Which sort does Java itself use?

Arrays.sort on primitive arrays such as int[] uses a dual-pivot quicksort, because stability does not matter for plain numbers and it is fast in practice. Arrays.sort on objects and Collections.sort use TimSort, a merge sort that finds runs already in order and merges them, because sorting objects by one field must be stable.

10Conclusion

Merge sort splits the array until every piece is a single, already sorted element, then merges pieces back together by always taking the smaller front element, choosing the left one on a tie. About log n levels of merges, each touching n elements, give O(n log n) time on every input, with O(n) extra space for one shared buffer, and the sort is stable. The clue to remember is a combining step that costs one linear pass: when two sorted halves can be merged cheaply, split, recurse and merge.

What to say in the interviewAbout 70 seconds aloud

Open with

Merge sort is divide and conquer. An array of zero or one element is already sorted. Otherwise I split the range at the middle, computed as lo plus hi minus lo over two to avoid overflow, sort each half recursively, and merge them.

Then, if they want more

The merge copies the range into a buffer and keeps one index at the front of each half. Each step copies the smaller front element back into the array, and on a tie it takes the left element, which keeps the sort stable. When one half runs out, I copy the rest of the other.

Each merge is linear in the size of its range, and splitting in half gives about log n levels, so the time is O(n log n) for every input, unlike quicksort's O(n squared) worst case. I allocate one buffer of size n up front and reuse it, so the extra space is O(n) plus O(log n) for the recursion.

Empty and single-element arrays return immediately, duplicates keep their order and negative numbers need nothing special. Insertion sort would be O(n squared) on a reversed array.

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 15 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Explain merge sort and write a complete working implementation.": https://scrivio-interview-library.netlify.app/data-structures/solutions/explain-merge-sort-and-write-a-complete-working-implementation-7450ec/