Quick revision
The short answer
The common sorts fall into a few families. Bubble, selection and insertion sort are simple, in place and O(n^2); merge sort, quick sort and heap sort reach O(n log n) by halving or by a heap; and counting and radix sort avoid comparisons and run in linear time when keys are small integers. They differ in worst case, extra memory and stability, and Java uses dual-pivot quick sort for primitives and stable TimSort for objects.
The solution
What it costs
| Sort | Best / average / worst | Extra space | Stable |
|---|---|---|---|
| Bubble (stops when a pass makes no swap) | n / n^2 / n^2 | O(1) | yes |
| Selection | n^2 / n^2 / n^2 | O(1) | no |
| Insertion | n / n^2 / n^2 | O(1) | yes |
| Merge | n log n in every case | O(n) | yes |
| Quick (random pivot) | n log n / n log n / n^2 | O(log n) stack | no |
| Heap | n log n in every case | O(1) | no |
| Counting (keys 0..k) | n + k in every case | O(k) | yes, written stably |
| Radix (d digits, base b) | d(n + b) in every case | O(n + b) | yes |
What to remember
We compared the common sorts through a few ideas. Insertion sort, like sorting a hand of cards, is simple, stable, in place and O(n^2), but nearly linear on almost sorted data. Merge sort is O(n log n) always and stable but needs O(n) memory, quick sort is usually fastest but has an O(n^2) worst case and is unstable, and heap sort guarantees O(n log n) in place without stability. Counting and radix sort beat n log n when keys are small integers. The clue to remember is that questions about order, neighbours or overlaps usually start with a sort, and small integer keys point to counting sort.
1What sorting means, told with a hand of playing cards
Think of a hand of playing cards dealt to you face down. You pick them up one at a time, and each time you slide the new card into its proper place among the cards you already hold. In a few seconds the hand is in order. You have just run a sorting algorithm, and you did it without any fear. Sorting means putting items in order by some key, numbers from smallest to largest, or people by age.
The list of sorting names in a textbook can feel long and frightening: bubble, selection, insertion, merge, quick, heap, counting, radix. The good news is that there are only a few ideas underneath. Some sorts repair the order one small step at a time; some cut the problem in half; one uses a special tree; and some do not compare items at all, they simply count. Once you see those ideas, the names become easy to remember, and the comparison the interviewer asks for follows from them.
We will use one small example the whole way, the six values 5, 2, 4, 6, 1, 3, drawn here as bars of different heights. Sorted, they must become the staircase 1, 2, 3, 4, 5, 6.
Six values in the order we are given them. Every sort below turns these bars into a staircase.
1We are given 5, 2, 4, 6, 1, 3. Sorted from smallest to largest they must read 1, 2, 3, 4, 5, 6.
Your turn
Solve it before you read on. Above is one example with the result expected 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.
2Three words that separate one sort from another
Before comparing sorts, we need three words, and we will take them one at a time. The first is comparison sort. A comparison sort learns about the data only by asking of two items, which one comes first? Insertion sort with the playing cards is one: each slide is a comparison. It can be proved that any comparison sort needs about n log n comparisons in the worst case, where n is the number of items, so O(n log n) is the best a comparison sort can promise. O(...) simply says how the work grows as n grows.
The second word is in place. A sort is in place when it needs almost no memory besides the array itself, a few variables, or at most a small stack. Sorting the cards in your hand is in place. Laying the cards out on a table into a second row would not be.
The third word is stable. A sort is stable when items with equal keys keep the order they had before. Suppose Ana, aged 30, comes before Raj, 25, and Bo, 30, in a list, and we sort by age. A stable sort gives Raj, Ana, Bo, keeping Ana before Bo because she was first. An unstable sort might give Raj, Bo, Ana. Stability matters when we sort by one field after another, for example orders by date and then by customer, and want each customer's orders to stay in date order.
Keep these three words in mind. Every sort below is a different answer to one question: how do we remove disorder with as little work and as little memory as possible, and do equal items keep their places?
3The simple sorts, and why insertion sort is the one to know
Bubble sort walks the array again and again, swapping neighbours that are in the wrong order, so the largest remaining value rises to the end on each pass like a bubble. Selection sort looks through the unsorted part for the smallest value and swaps it into the next place. Both are easy to write, both are in place, and both need about n x n steps, O(n^2), on ordinary input. Bubble sort is stable; selection sort is not, because its long swaps can jump one equal item past another.
Insertion sort is our playing cards, and it is the simple sort worth knowing well. It keeps a sorted part at the front of the array and takes the next value, slides every larger value in the sorted part one place right, and drops the new value into the gap. The picture runs the real program on our six values.
Each frame picks up the next value and slides the larger values of the sorted part one place right until the new value fits.
- sorted part
- a[0..0]
1At the start the first card, 5, is a sorted hand of one. Everything to its right is still to be picked up.
- picked up
- 2
- slides
- 1
- sorted part
- a[0..1]
2We pick up 2. The 5 is larger, so it slides one place right and 2 drops into index 0. The sorted part is now 2, 5.
- picked up
- 4
- slides
- 1
- sorted part
- a[0..2]
3We pick up 4. Only the 5 is larger, so it slides right once and 4 drops in between 2 and 5.
- picked up
- 6
- slides
- 0
- sorted part
- a[0..3]
4We pick up 6. The card to its left, 5, is smaller, so nothing moves at all. Already placed cards cost almost nothing.
- picked up
- 1
- slides
- 4
- sorted part
- a[0..4]
5We pick up 1. All four cards in the sorted part are larger, so each slides one place right and 1 drops into index 0.
- picked up
- 3
- slides
- 3
- sorted part
- a[0..5]
6We pick up 3. The 6, 5 and 4 slide right, the 2 is smaller and stops the slide, and 3 drops into index 2. The array is sorted.
Now count the slides in the picture. They are 1, 1, 0, 4 and 3, eleven in all. Each slide repairs exactly one pair of values that were in the wrong order, so the work is as large as the disorder. On random data that is about n^2 / 4 slides, O(n^2). But look at the frame where we pick up 6: nothing moves. On an array that is already nearly sorted, almost every pick-up looks like that, and insertion sort runs in close to O(n). It is stable and in place too.
A beginner often asks why anyone would use an O(n^2) sort. The answer is in that frame. For very small arrays, or arrays that are almost in order, insertion sort's tiny loop beats the clever sorts, which is why real libraries switch to it for short pieces inside a bigger sort.
4Merge sort, which cuts the work in half
The fast sorts begin from a different idea. Sorting six cards is hard, but merging two piles that are already sorted is easy: look at the top card of each pile, take the smaller, and repeat. Merge sort uses that. It cuts the array in the middle, sorts each half by the same method, and merges the two sorted halves. A piece of one value is already sorted, so the cutting stops there.
The cuts are drawn level by level; the merges are shown in the order the recursive program performs them.
- pieces
- [5 2 4 6 1 3]
1Merge sort starts with the whole array as one unsorted piece. Its first job is only to cut, not to sort.
- pieces
- [5 2 4] [6 1 3]
2The array is cut in the middle into two halves of three. Nothing has moved yet; we have only drawn a line.
- pieces
- [5 2] [4] [6 1] [3]
3Each half is cut again. The cut is at the middle index, so a piece of three becomes a piece of two and a piece of one.
- pieces
- [5] [2] [4] [6] [1] [3]
4Now every piece holds one value, and a piece of one value is already sorted. The cutting is over and the merging begins.
- pieces
- [2 5] [4] [6] [1] [3]
5Merging [5] and [2] compares their fronts, takes the smaller 2 first, then 5. The piece [2 5] is sorted.
- pieces
- [2 4 5] [6] [1] [3]
6Merging [2 5] with [4] takes 2, then 4 because 4 < 5, then 5. The whole left half is now sorted.
- pieces
- [2 4 5] [1 6] [3]
7The right half goes the same way. Merging [6] and [1] gives [1 6].
- pieces
- [2 4 5] [1 3 6]
8Merging [1 6] with [3] gives [1 3 6]. Now both halves are sorted, each in its own three places.
- pieces
- [1 2 3 4 5 6]
9The last merge compares the fronts 2 and 1, takes 1, then 2, 3, 4, 5 and 6, always the smaller front. The array is sorted.
Why is it fast? Look at the frames as levels. Cutting six values in half again and again takes about log n levels, here three, because each level halves the pieces. On each level the merges together touch every value once, n steps. So the whole sort takes about n log n steps, O(n log n), and it does so in every case, sorted input or not.
Merge sort is stable, because when the two fronts are equal we take the one from the left pile first. Its cost is memory: merging two halves of an array needs a spare buffer to write into, O(n) extra space, so it is not in place.
5Quick sort and heap sort, the other fast ways
Quick sort turns merge sort around. Instead of cutting first and doing the work while merging, it does the work first. It chooses one value, the pivot, and moves every smaller value to its left and every larger value to its right. This step is called partitioning. After it, the pivot is in its final place, and the two sides can be sorted separately with the same method, with no merging at all.
One partition pass with the last value as the pivot. After it, the two sides are sorted separately in the same way.
- pivot
- 3
1The pivot is the last value, 3. Everything left of i will be smaller than 3; i starts at 0 because nothing is placed yet.
- pivot
- 3
2j looks at 5. It is not smaller than 3, so it stays where it is and i does not move.
- pivot
- 3
3j looks at 2, which is smaller than 3. We swap it into place i, index 0, and move i on to index 1.
- pivot
- 3
4j passes 4 and then 6. Neither is smaller than 3, so both stay and i stays on index 1.
- pivot
- 3
5j looks at 1, which is smaller than 3. We swap it with the 5 at index i, so 1 joins the small part, and i moves to 2.
- pivot
- 3
6Finally the pivot swaps into index i. 3 is now in its final place, with smaller values left and larger values right.
Partitioning happens inside the array with swaps, so quick sort is in place apart from the recursion, and its inner loop is very tight. On average it is O(n log n) and usually the fastest sort in practice. Here is the question a careful beginner should ask: what if the pivot is a bad choice? If it is always the smallest or largest value, for example the last value of an already sorted array, each partition peels off only one item and the sort becomes O(n^2). Choosing the pivot at random, or as the middle of three values, makes that very unlikely. Its long swaps also make quick sort unstable.
Heap sort uses a different tool, a max-heap, which is a tree kept inside the array where every parent is at least as large as its children, so the largest value is always at the root. Heap sort builds the heap, swaps the root to the end of the array, repairs the heap, and repeats. It is O(n log n) in every case and in place, but it jumps around memory, which makes it slower than quick sort on real machines, and it is not stable.
6Sorting without comparing, counting sort and radix sort
The n log n limit applies only to sorts that compare. If the keys are small whole numbers, such as grades from 0 to 3, we can skip comparing altogether. Picture a teacher with a pile of marked papers who simply puts four boxes on the desk, one per grade, and drops each paper in its box. Counting sort does exactly that with counters.
Each box is a counter for one grade, numbered 0 to 3 above it. We count first, then write each grade back as many times as it was counted.
- grades
- 3 0 2 3 1 0
- written
- nothing yet
1We read the grades 3, 0, 2, 3, 1, 0 once and add one to the counter for each. Two 0s, one 1, one 2 and two 3s.
- grades
- 3 0 2 3 1 0
- written
- 0 0
2Counter 0 says two, so we write 0 twice at the front of the array. No two grades were ever compared.
- grades
- 3 0 2 3 1 0
- written
- 0 0 1
3Counter 1 says one, so we write a single 1 after the zeros.
- grades
- 3 0 2 3 1 0
- written
- 0 0 1 2
4Counter 2 says one, so we write a single 2.
- grades
- 3 0 2 3 1 0
- written
- 0 0 1 2 3 3
5Counter 3 says two, so we write 3 twice. The array now reads 0, 0, 1, 2, 3, 3, sorted in two passes.
Counting sort reads the input once to count, then walks the counters once to write back, so it takes O(n + k) time, where k is the number of possible keys, and O(k) extra space for the counters. With six grades and four possible values it did ten small steps and never compared two grades with each other. It is ideal for ages, marks, or the three colours of a flag problem, but useless when keys range over millions of values.
Radix sort extends the idea to bigger numbers by sorting on one digit at a time, the last digit first, with a stable counting sort at each step. For numbers of d digits it takes about d passes, O(d (n + b)) for digits in base b. Both sorts depend on knowing the shape of the keys, so they are tools for special cases, not general replacements.
7The sorts side by side, and how Java chooses
The table gathers what we have seen. Read it slowly, one column at a time: no single sort wins every column, and that is the real answer to the question. Each fast sort gives something up, memory, stability or a guaranteed worst case.
| Sort | Best / average / worst | Extra space | Stable |
|---|---|---|---|
| Bubble (stops when a pass makes no swap) | n / n^2 / n^2 | O(1) | yes |
| Selection | n^2 / n^2 / n^2 | O(1) | no |
| Insertion | n / n^2 / n^2 | O(1) | yes |
| Merge | n log n in every case | O(n) | yes |
| Quick (random pivot) | n log n / n log n / n^2 | O(log n) stack | no |
| Heap | n log n in every case | O(1) | no |
| Counting (keys 0..k) | n + k in every case | O(k) | yes, written stably |
| Radix (d digits, base b) | d(n + b) in every case | O(n + b) | yes |
In real Java we rarely write a sort; we choose the library call. Arrays.sort on primitives such as int[] uses a dual-pivot quick sort, a quick sort with two pivots, because plain numbers do not need stability and speed matters most. Arrays.sort on objects, and List.sort, use TimSort, a merge sort that finds runs already in order and uses insertion sort for short pieces, because objects often need stability.
Let us read the program in the order it runs. insertionSort is our playing cards: value is the card picked up, the while loop slides larger values right while j walks left, and a[j + 1] = value drops the card into the gap. The condition j >= 0 comes first so that we never read a[-1] when the new value is the smallest so far.
countingSort makes one counter per possible key, counts in one pass, and then writes each key back as many times as it was counted. The loop while (count[v]-- > 0) tests the counter and then lowers it, so it runs exactly count[v] times.
The last two calls use the library. The int array is sorted by dual-pivot quick sort and prints [-2, 0, 7, 9]. The list of people is sorted by age with TimSort, and because TimSort is stable, Ana stays before Bo, so it prints [Raj, Ana, Bo].
8How to recognise a problem that wants a sort
Many interview problems become easy once the input is in order, and the clue is usually a question about order, neighbours or overlaps. Merging overlapping meetings, finding two numbers with a given sum, grouping anagrams by their sorted letters, or finding the closest pair of values all start with an O(n log n) sort that turns a slow search into one walk along the array.
Some words point to a particular sort. A phrase like values from 0 to k, or only three colours, hints at counting sort. A request for only the k largest values, or the k-th smallest, means a full sort is more than we need; a heap, or quickselect, which is quick sort's partition applied to one side only, is cheaper. A question about counting pairs that are out of order is answered by the merge step of merge sort, which can count them while it merges. And a linked list that must be sorted points to merge sort, because it never needs to jump to a position.
9Follow-up questions
Why can no comparison sort beat n log n?
Think of the sort as a game of yes or no questions. Six values can arrive in 720 different orders, and the sort must be able to tell every one of them apart, because each needs different moves to fix. Each comparison has only two answers, so at best it halves the orders still possible. Halving 720 down to 1 takes about ten questions, and in general telling n! orders apart takes about log2(n!) comparisons, which grows like n log n. Counting and radix sort escape the limit because they read the key values directly instead of comparing.
Which sort would you use for a linked list?
Merge sort. It only ever needs to walk forward: we split the list with a slow and a fast pointer to find the middle, and we merge by relinking nodes, so no extra buffer is needed and it stays O(n log n). Quick sort and heap sort depend on jumping to positions, which a linked list cannot do cheaply.
Which sort is best for data that is almost sorted?
Insertion sort, because its work equals the number of slides, and a nearly sorted array needs very few, as the frame where we picked up 6 showed. TimSort, which Java uses for objects, exploits the same fact on large inputs by finding the runs that are already in order and merging them.
10Conclusion
We compared the common sorts through a few ideas. Insertion sort, like sorting a hand of cards, is simple, stable, in place and O(n^2), but nearly linear on almost sorted data. Merge sort is O(n log n) always and stable but needs O(n) memory, quick sort is usually fastest but has an O(n^2) worst case and is unstable, and heap sort guarantees O(n log n) in place without stability. Counting and radix sort beat n log n when keys are small integers. The clue to remember is that questions about order, neighbours or overlaps usually start with a sort, and small integer keys point to counting sort.
Open with
I would group them in three families. The simple ones are bubble, selection and insertion sort. They are in place and quadratic on average; insertion sort is the useful one, because it is close to linear on nearly sorted data and fast on small arrays, which is why libraries use it for small pieces.
Then, if they want more
Then the n log n comparison sorts. Merge sort splits, sorts the halves and merges; it is n log n in every case and stable, but needs a linear buffer.
Quick sort partitions around a pivot in place and is usually fastest, but its worst case is quadratic with bad pivots, so I pick the pivot randomly, and it is not stable.
Heap sort builds a max-heap and moves the top to the end repeatedly; it is n log n in every case with constant extra space, but cache-unfriendly and unstable. Finally, counting and radix sort do not compare, so with small integer keys they run in linear time.
Comparison sorts cannot beat n log n, because they must tell n factorial orders apart with yes or no answers. In Java, Arrays.sort uses dual-pivot quick sort for primitives and TimSort, a stable merge sort, for objects. So I choose by the constraint: stability, memory, a worst-case guarantee, or the shape of the keys.
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 20 times in that collection. How it is counted
- Official documentation
- Comparator (Java 21), Arrays (Java 21), ArrayList (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 "Describe the common sorting techniques and how they compare.": https://scrivio-interview-library.netlify.app/data-structures/solutions/describe-the-common-sorting-techniques-and-how-they-compare-84c203/