Quick revision
The short answer
Merge sort and quick sort are both O(n log n) divide and conquer sorts, but they put the work in different places. Merge sort splits by position and does its work while merging, so it is O(n log n) in every case and stable, at the cost of an O(n) buffer. Quick sort does its work while partitioning around a pivot, so it sorts in place with O(log n) stack and is usually faster, but it is not stable and degrades to O(n^2) with bad pivots, which random pivots make very unlikely.
The solution
What it costs
| Aspect | Merge sort | Quick sort |
|---|---|---|
| Where the work is done | merging sorted halves | partitioning around a pivot |
| Best and average time | O(n log n) | O(n log n) |
| Worst time | O(n log n) | O(n^2), very unlikely with random pivots |
| Extra space | O(n) buffer | O(log n) stack on average |
| Stable | yes | no |
| Speed in practice | steady, more copying | usually the fastest for arrays |
| Linked lists | excellent, no buffer needed | poor, needs jumping around |
| Used by Java for | objects (TimSort) | primitives (dual-pivot quick sort) |
What to remember
Merge sort and quick sort are two ways of dividing and conquering. Merge sort splits by position and does its work while merging, so it is O(n log n) in every case and stable, but needs an O(n) buffer. Quick sort does its work while partitioning around a pivot, so it sorts in place with O(log n) stack and is usually faster, but it is not stable and is O(n^2) in the worst case, which random pivots make very unlikely. The clue to remember: stability, a guarantee, a linked list or data on disk point to merge sort; fast in-memory sorting of plain numbers points to quick sort.
1Two ways to sort a pile of exam papers
Imagine a teacher with a tall pile of marked exam papers to put in order of marks, and two helpers. The first way is to cut the pile in half without looking, hand one half to each helper, and ask each to sort their half. When the two sorted halves come back, the teacher puts them side by side and merges them: look at the top paper of each pile, take the one with the lower mark, and repeat until both piles are empty. That is merge sort.
The second way is to pick one paper, say a mark of 50, and before handing anything over, put every paper below 50 on the left and every paper above it on the right, with the 50 in between. Now each helper sorts one side, and when they return, there is nothing left to do: the left pile, the 50 and the right pile are already in order. That is quick sort, and the chosen paper is called the pivot.
Both ways follow a plan called divide and conquer. We divide a problem into smaller problems of the same kind, solve each one the same way, and combine the answers. The helpers themselves split their piles again, and so on, until a pile has one paper, which is sorted by itself. Notice the one real difference: merge sort does its thinking after the split, in the merge, while quick sort does its thinking before the split, in the partition. Keep that in mind, because the rest of the article grows from it.
We will use one small array for both sorts, [38, 27, 43, 3, 9, 82, 10], and the pictures follow exactly what the Java at the end does on it.
Your turn
Solve it before you read on. Start by writing one small example and the result you expect for it. If the question leaves something open, such as an empty input or repeated values, note what you would ask the interviewer. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How merge sort works inside
Merge sort splits the array at its middle index into a left half and a right half, sorts each half by calling itself, and then merges the two sorted halves. The split never looks at the values, so it is quick and always even. In the code below, the range [lo, hi) means from index lo up to, but not including, hi, and the middle is (lo + hi) / 2.
The picture shows the array after each merge, in the order the code really does them. Watch how the sorted runs grow from pairs to halves to the whole array.
Each frame is the array after one merge, in the order the code performs them. The part just merged is marked; earlier merged runs are shown as finished.
1The code splits [0, 7) at mid 3 into 38 27 43 and 3 9 82 10, then keeps splitting until every piece is one number, which is already sorted.
2The first merge joins 27 and 43, indexes 1 and 2. They are already in order, so the array does not change, but now 27 43 is a sorted run.
3Next 38 is merged with the run 27 43. The smaller fronts are taken first, giving 27 38 43 in indexes 0 to 2. The left half is sorted.
4The right half splits into 3 9 and 82 10. Merging 3 with 9 changes nothing, but it makes 3 9 a sorted run.
5Merging 82 with 10 takes the 10 first, because it is smaller, so indexes 5 and 6 become 10 82.
6The runs 3 9 and 10 82 are merged into 3 9 10 82, so the right half is sorted too. Two sorted halves remain.
7The last merge joins 27 38 43 with 3 9 10 82 and gives the sorted array, 3 9 10 27 38 43 82.
Let us count the levels. Seven numbers split into pieces of three and four, those into pieces of one and two, and those into single numbers, so there are three levels of merging. At each level every number is copied into the buffer once, so each level costs about n steps. Halving n repeatedly reaches 1 after about log2(n) halvings, read as log base two of n, so the total is O(n log n). Because the halves are always even, this is true for every input, sorted, reversed or random.
A beginner often asks why merge sort needs extra memory at all. Could we not merge the two halves inside the array? Let us try. If we write the 3 into index 0 straight away, we overwrite the 27, which we have not yet placed. To avoid losing values, merge sort writes into a separate buffer of n places and copies back afterwards, so its extra space is O(n).
3The merge step up close
The merge is where merge sort does its real work, so let us watch the last one slowly. We have two sorted runs, 27 38 43 and 3 9 10 82. One finger, i, rests on the front of the left run and another, j, on the front of the right run. At each step we compare the two front values, copy the smaller into the buffer, and move that finger on. Each comparison places one number for good.
The array holds two sorted runs, 27 38 43 and 3 9 10 82. The two fronts being compared are marked, and the buffer shows what has been taken.
- buffer
- empty
1The last merge starts with i on the front of the left run, 27, and j on the front of the right run, 3. The buffer is empty.
- buffer
- 3
- took
- 3 from the right
23 is smaller than 27, so the 3 from the right run goes into the buffer and j moves on to 9.
- buffer
- 3 9
- took
- 9 from the right
39 is smaller than 27, so 9 is taken from the right run and j moves on to 10.
- buffer
- 3 9 10
- took
- 10 from the right
410 is smaller than 27, so 10 is taken and j moves on to 82.
- buffer
- 3 9 10 27
- took
- 27 from the left
5Now 27 is smaller than 82, so for the first time we take from the left run, and i moves on to 38.
- buffer
- 3 9 10 27 38
- took
- 38 from the left
638 is smaller than 82, so 38 goes into the buffer and i moves on to 43.
- buffer
- 3 9 10 27 38 43
- took
- 43 from the left
743 is smaller than 82, so 43 is taken. The left run is used up, which ends the comparing loop.
- buffer
- 3 9 10 27 38 43 82
8The leftover 82 is copied into the buffer, and
System.arraycopycopies the buffer back over indexes 0 to 6. The array is sorted.
The frames show the whole idea. The right run wins three times in a row, because 3, 9 and 10 are all smaller than 27. Then the left run wins three times, until it is used up, and the leftover 82 is copied in without any comparison. Seven numbers were placed with six comparisons. Merging two sorted runs never needs more than one comparison per number placed, which is why each level costs O(n).
There is one quiet detail here that matters a great deal. When the two front values are equal, the code takes from the left run, because it tests a[i] <= a[j]. The left run holds the numbers that came earlier in the original array, so equal values keep their original order. A sort with this property is called stable, and merge sort is stable for exactly this reason. It matters when we sort records, such as employees sorted by department after being sorted by name: a stable sort keeps the names in order within each department.
4How quick sort works inside
Quick sort picks one value as the pivot and partitions the range, which means rearranging it so that every value smaller than the pivot comes before it and every other value after it. The pivot then sits in its final sorted place and never moves again. Then quick sort sorts the left part and the right part the same way, and there is no merge at all.
Our code chooses the pivot at random and uses the Lomuto partition. It swaps the pivot to the end of the range, then walks j along the range with a second index, store, marking where the next smaller value should go. Whenever a[j] is smaller than the pivot, it swaps a[j] into store and moves store on. At the end it swaps the pivot into store. The picture follows the run seeded with new Random(1), as in main.
Each frame shows the array after one step of the run seeded with new Random(1). Marked cells are pivots already in their final places.
- range
- 0..6
- pivot
- 9
1The random choice for the whole array, indexes 0 to 6, picks index 4, so the pivot is 9.
- range
- 0..6
- pivot
- 9
2The pivot 9 is swapped to the end. Then j scans indexes 0 to 5, and store marks where the next smaller value will go.
- range
- 0..6
- pivot
- 9
- smaller
- 3
3Only 3 is smaller than 9, so at j = 3 it is swapped into index 0 and store moves to 1. Everything else is larger and stays put.
- left part
- 0..0
- right part
- 2..6
4The pivot is swapped into index 1, its final place: 3 on its left, five larger values on its right. The single 3 is sorted already.
- range
- 2..6
- pivot
- 82
- right part
- empty
5For indexes 2 to 6 the random pivot is 82, the largest value. Nothing is larger, so 82 ends at index 6 and one side is empty: an unlucky split.
- range
- 2..5
- pivot
- 38
6For indexes 2 to 5 the pivot is 38. The values 27 and 10 are swapped to the front, and 38 lands at index 4, with 43 alone on its right.
- range
- 2..3
- pivot
- 27
- result
- sorted
7For indexes 2 and 3 the pivot is 27. The 10 is smaller, so 27 lands at index 3. Every value is now in its final place, with no merge needed.
The fourth frame shows the moment that defines quick sort: after one pass, 9 is in its final place, with 3 on its left and five larger values on its right. Each partition puts one pivot exactly where it belongs and splits the problem in two.
The fifth frame shows quick sort's weakness. The random pivot for indexes 2 to 6 happened to be 82, the largest value, so everything went to one side and the other side was empty. That partition did a pass of work and shrank the problem by only one number. One unlucky pivot costs a little; a bad pivot at every level is the real danger, and we will look at it next.
Notice also what partitioning does to equal values. Swaps can carry a value far across the array, past others equal to it, so their original order is not kept. Quick sort is not stable. Its gift is that every swap happens inside the array, so it needs no buffer, only the stack of recursive calls.
5Where the time goes in the best, average and worst cases
Both sorts cost about n steps per level of splitting, so the real question is how many levels there are. For merge sort we already know: the split is by position, always even, so there are about log2(n) levels in every case, and merge sort is O(n log n) in the best, average and worst case alike.
For quick sort the number of levels depends on the pivots. If every pivot lands near the middle, each part is about half the size, there are about log2(n) levels, and the time is O(n log n). Now the beginner's question: what if every pivot is the smallest or largest value, like the 82 in our picture, every time? Then each partition peels off only the pivot, there are n levels instead of log n, and the passes cost n, then n - 1, then n - 2 and so on, which adds up to about n^2 / 2 steps. That is O(n^2).
When does that happen? With a fixed choice such as always taking the first element as the pivot, an array that is already sorted does it every time, and sorted input is very common in real programs. Choosing the pivot at random protects us: no particular input can force bad pivots, and a run of bad luck long enough to matter is astronomically unlikely. So randomised quick sort is O(n log n) on average for every input, with an O(n^2) worst case that we can mention honestly but need not fear.
6Merge sort and quick sort side by side
The table puts the two sorts next to each other on the points interviewers ask about. Each row follows from the idea we began with: merge sort works after splitting, quick sort before.
| Aspect | Merge sort | Quick sort |
|---|---|---|
| Where the work is done | merging sorted halves | partitioning around a pivot |
| Best and average time | O(n log n) | O(n log n) |
| Worst time | O(n log n) | O(n^2), very unlikely with random pivots |
| Extra space | O(n) buffer | O(log n) stack on average |
| Stable | yes | no |
| Speed in practice | steady, more copying | usually the fastest for arrays |
| Linked lists | excellent, no buffer needed | poor, needs jumping around |
| Used by Java for | objects (TimSort) | primitives (dual-pivot quick sort) |
So why is quick sort usually faster, when both are O(n log n) on average? Its inner loop is a single comparison and an occasional swap, it walks through memory in order, and it never copies numbers into a buffer and back. That suits the caches inside a processor, the small fast memories that reward reading neighbouring values. Merge sort makes a similar number of comparisons but moves every number into the buffer and back at every level.
Merge sort wins elsewhere. Its guarantee never depends on luck, its stability is exactly what multi-key sorting of records needs, and on a linked list its merge simply relinks nodes, so it needs no buffer at all. Java itself makes the same choice: Arrays.sort on an int array uses a tuned dual-pivot quick sort, while sorting objects uses TimSort, a merge sort that also spots runs that are already in order.
7Both sorts in Java
The class below writes merge sort with one shared buffer and quick sort with a random pivot and the Lomuto partition. main sorts the same array with both and checks a single number, and each comment shows what that line prints.
Let us read mergeSort in the order it runs. If the range holds fewer than two numbers, it is already sorted and we return; this is what stops the recursion. Otherwise we find mid with (lo + hi) >>> 1, an unsigned shift that halves the sum safely even for huge indexes, and sort the two halves by calling ourselves.
Then comes the merge, exactly as in the close-up picture. i walks the left half, j the right half, and k the buffer. The first while loop takes the smaller front each time, using <= so ties come from the left and the sort stays stable. The next two loops copy whatever is left in either half, and System.arraycopy copies the merged run from the buffer back into the array.
Now quickSort. If lo >= hi the range has at most one number, so we return. Otherwise we swap a random index from lo to hi into position hi, so the pivot sits at the end. store starts at lo, and the for loop moves every smaller value into store, one by one. The final swap puts the pivot at store, its final place, and we sort the parts on each side of it.
Passing new Random(1) makes the run repeatable, which is how the picture above could follow it exactly. In real code we would simply call Arrays.sort, which picks the right algorithm for us.
8How to recognise which one a problem needs
Choose merge sort when stability matters, such as sorting records by a second key while keeping the order of the first, when a guaranteed worst case matters more than average speed, when sorting a linked list, or when the data does not fit in memory and must be sorted in chunks that are then merged from disk, which is called external sorting. Choose quick sort for arrays of plain numbers in memory, where speed and low memory matter and stability does not.
Their inner steps also solve problems of their own, and spotting them is a skill interviewers like to test. The merge step solves merge two sorted arrays, merge k sorted lists, and count inversions, the number of pairs that are out of order, which we can count while merging every time a right-half value jumps ahead of left-half values. The partition step solves find the k-th largest element through quickselect, which partitions and then continues into only the side that holds k, for O(n) average time, and the Dutch national flag problem of sorting 0s, 1s and 2s, which is a three-way partition.
So when you read a new problem, listen for its clues. Words like merge, sorted lists, or pairs out of order point to the merge step. Words like k-th largest, or move these values before those, point to the partition.
9Follow-up questions
Can quick sort be made stable, or merge sort made to work in place?
Both are possible, but each costs the algorithm its main strength. Quick sort becomes stable if we partition into new lists instead of swapping, keeping each value's original order within its list, but then it needs O(n) extra memory, which was its advantage. Merging in place without a buffer can be done, but the known methods are complicated and slower in practice. That is why libraries simply choose the algorithm whose natural strengths fit the data.
How does introsort protect quick sort's worst case?
Introsort starts as an ordinary quick sort but counts how deep the recursion has gone. If the depth passes about 2 log2(n), which only happens after many bad pivots in a row, it switches to heap sort for that part, which is O(n log n) in every case. It also uses insertion sort for very small parts, where simple code is fastest. C++'s std::sort is built this way, so it keeps quick sort's everyday speed and still has a guaranteed worst case.
Which one copes better with many duplicate values?
Merge sort does not care about duplicates at all. A plain two-way quick sort can slow down badly when most values equal the pivot, because they all go to one side and the split becomes lopsided. A three-way partition, which groups values less than, equal to and greater than the pivot, fixes this: all the copies of the pivot are finished in one pass and never looked at again, so many duplicates actually make quick sort faster.
10Conclusion
Merge sort and quick sort are two ways of dividing and conquering. Merge sort splits by position and does its work while merging, so it is O(n log n) in every case and stable, but needs an O(n) buffer. Quick sort does its work while partitioning around a pivot, so it sorts in place with O(log n) stack and is usually faster, but it is not stable and is O(n^2) in the worst case, which random pivots make very unlikely. The clue to remember: stability, a guarantee, a linked list or data on disk point to merge sort; fast in-memory sorting of plain numbers points to quick sort.
Open with
Both are divide and conquer and O(n log n) on average, but they do the work in different places. Merge sort splits the array in half by position, sorts each half, and does the real work merging the two sorted halves with two pointers into a buffer.
Then, if they want more
Because the split is always even, it is n log n in the best, average and worst case, and taking from the left half on ties makes it stable. The cost is an O(n) buffer.
Quick sort picks a pivot and partitions, smaller values to the left and the rest to the right, so the pivot lands in its final place, then sorts each side, with nothing to merge. It works in place with O(log n) stack on average, and its tight loop usually makes it the fastest for arrays.
But a bad pivot every time gives n squared, for example the first element on sorted input, so I choose pivots at random. It is also not stable. So I choose merge sort for stability, a worst-case guarantee, linked lists or external sorting, and quick sort for in-memory arrays of primitives.
Java does the same, with dual-pivot quick sort for primitives and TimSort for objects.
About this answer
- Last updated
- 14 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 18 times in that collection. How it is counted
- Official documentation
- Random (Java 21), Arrays (Java 21), java.util, package documentation
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 "Compare merge sort with quick sort.": https://scrivio-interview-library.netlify.app/data-structures/solutions/compare-merge-sort-with-quick-sort-517db3/