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

Write an implementation of quick sort.

1What the task asks, told with a class lining up by height

Imagine a sports teacher who wants a class standing in order of height. Instead of comparing every child with every other, the teacher picks one child and says: everyone shorter than this child, stand on the left; everyone else, on the right. The chosen child now stands exactly where they belong in the final line and never needs to move again. Then the teacher does the same with the group on the left and the group on the right, and with their groups, until every group has one child. That is quick sort, and the chosen child is called the pivot.

Our task is to write it for an int array, sorting it in ascending order. We will use one example throughout: [7, 2, 1, 6, 8, 5, 3, 4], which must become [1, 2, 3, 4, 5, 6, 7, 8]. Notice how small each job is. A single round of the teacher's instruction only asks, for each value, smaller or not? Everything else is repetition.

PictureThe example array before and after

Top row: the array we are given. Bottom row: the same eight values after sorting, in place.

  1. 7216853412345678

    1The top row is the input, 7 2 1 6 8 5 3 4. The bottom row is what quickSort must leave in the same array: 1 2 3 4 5 6 7 8.

What to assume

Should we sort in place, inside the given array, or may we return a new one?
In place.
Can the array hold duplicates and negatives?
Yes to both. Large inputs in which many values are equal are a known weakness of this implementation.
Can it be large, or already sorted?
Yes, up to millions of values and possibly sorted already.
Must equal values keep their original order, which is called being stable?
No.

A careful candidate asks a few questions first. Should we sort in place, inside the given array, or may we return a new one? In place, which is the point of quick sort. Can the array hold duplicates and negatives? Yes to both. Can it be large, or already sorted? Yes, up to millions of values and possibly sorted already, which matters for the choice of pivot, as we will see. Must equal values keep their original order, which is called being stable? No; quick sort is not stable, and if stability were required we would choose merge sort instead.

2How to spot the partitioning pattern inside quick sort

This question names its algorithm, so a beginner may think there is no pattern to spot, only code to remember. But remembering code line by line is fragile under interview pressure. What helps is to recognise the one idea quick sort is built on, because then the code can be rebuilt from the idea rather than from memory.

So let us read the clues. The first is the word sort itself, which tells us the result is an ordering of the same values, with nothing added or removed. The second is the name quick sort, which points to one particular way of ordering: choose a pivot and split the values around it. The third is the unspoken expectation that it works in place, meaning we rearrange the values inside the array we were given, with no second array.

Put together, these clues point to the sorting and intervals family, and inside it to a pattern called partitioning. To partition an array is to rearrange it so that every value passing a test comes before every value failing it, using one index that marks the boundary between the two groups. Here the test is smaller than the pivot. Quick sort is simply a partition applied again and again to smaller and smaller ranges.

The general rule to carry to new problems is this. Whenever a question asks you to split an array into groups by a test, such as smaller than x first, even numbers first, or zeros to the end, one pass with a boundary index does it in O(n) time and O(1) extra space. The same partition, applied to only one side, gives quickselect, which finds the k-th smallest value.

Other sorts look similar but are built on different ideas. Merge sort is also divide and conquer, but it splits by position and does its work while merging, so it needs a buffer. Selection sort, which repeatedly picks the smallest remaining value, is simpler but always slow.

3The honest first attempts, a slow sort and a copying quick sort

The simplest correct sort is selection sort: find the smallest value and swap it to the front, then the smallest of the rest, and so on. It needs no thought about pivots, but it always makes about n^2 / 2 comparisons, so a million values take minutes rather than a fraction of a second. It is a fine brute force to name, and a good baseline to beat.

The first quick sort most people write is easier to get right, because it copies values into new lists instead of swapping. It takes the first value as the pivot, puts every value into a less, equal or greater list, sorts less and greater by calling itself, and joins the three lists.

Java
static List<Integer> quickSortCopy(List<Integer> list) {
if (list.size() <= 1) return list;
int pivot = list.get(0); // first element as pivot
List<Integer> less = new ArrayList<>(), equal = new ArrayList<>(), greater = new ArrayList<>();
for (int x : list) {
if (x < pivot) less.add(x);
else if (x == pivot) equal.add(x);
else greater.add(x);
}
List<Integer> out = new ArrayList<>(quickSortCopy(less)); // new lists at every level
out.addAll(equal);
out.addAll(quickSortCopy(greater));
return out;
}

Let us run it on our example by hand. The pivot is 7, so less is [2, 1, 6, 5, 3, 4], equal is [7] and greater is [8]. Then less is sorted the same way with pivot 2, and so on. It is correct, and the equal list even handles duplicates neatly. Counting the work at one level, the loop looks at each of the eight values once, so a level costs O(n).

But there are two kinds of waste. First, every level builds new lists and copies values into them, so the code spends much of its time copying and uses O(n) extra memory at each level. Second, and more dangerous, is the pivot, as the next section shows on an array that is already sorted, a very common input in real programs.

4Getting to the in-place version, one problem at a time

Let us begin with the danger we left open. The picture runs the copying version on the sorted array 1 to 8, where the first value is always the smallest.

Step throughA first-element pivot on an already sorted array

The marked cell is the pivot; the cells after it all land in the greater list. Each level removes only one value.

  1. 1021324354657687
    level
    1
    values seen
    8

    1The copying version takes the first value, 1, as the pivot. All seven other values are larger, so the less list is empty and greater holds 2 to 8.

  2. 1021324354657687
    level
    2
    values seen
    8 + 7

    2At the next level the pivot is 2, again the smallest, and greater holds 3 to 8. The problem shrank by only one value.

  3. 1021324354657687
    level
    3
    values seen
    8 + 7 + 6

    3At the third level the pivot is 3 and greater holds 4 to 8. Every level copies the rest of the list into new lists.

  4. 1021324354657687
    levels
    7, plus the last call
    values seen
    35

    4This continues until the list has one value. The loops look at 8 + 7 + 6 + 5 + 4 + 3 + 2 = 35 values across seven levels, about n^2 / 2.

Each level removes only the pivot. The loops look at 35 values for just 8 numbers, about n^2 / 2, and the recursion is n levels deep, which can overflow the stack for large arrays. So we have three problems to fix: the copying, the bad pivot and the deep recursion. Let us take them one at a time.

To remove the copying, we partition inside the array with the Lomuto scheme. We put the pivot at the last position, hi, and keep an index called store with one promise: every value before store is smaller than the pivot. A second index, j, walks from lo to hi - 1. Whenever a[j] is smaller than the pivot, we swap it into position store and move store on by one, which keeps the promise. When j finishes, all the smaller values sit before store and all the others between store and hi - 1.

Now the question a beginner asks. Why move the pivot to the end before scanning? Could we not leave it where it is? Let us try. If the pivot stayed at index 5 in our example, j would pass over it in the middle of the scan, and a swap could carry it to some other index, so we would no longer know where it is. Parked at hi, outside the range j visits, it stays put. After the scan, one swap of a[store] and a[hi] puts it at store, exactly between the two groups, which is its final place.

To remove the bad pivot, we pick the pivot at a random index from lo to hi and swap it to the end. Why does randomness help? A random pivot lands in the middle half of the values half the time, and each such landing cuts the range by at least a quarter, so on average the ranges shrink quickly and there are about log n levels. No input, sorted or reversed, can force bad pivots, because the input does not choose them.

To keep the recursion shallow, we call ourselves only on the smaller of the two parts, and handle the larger part by looping, changing lo or hi and partitioning again. The smaller part has at most half the values, so each nested call at least halves the size, and the calls can never be more than about log2(n) deep, even on an unlucky run.

Why is the result sorted? After a partition, the pivot is in its final place, everything before it is smaller and everything after it is not. Sorting the two parts separately cannot break that, because no value ever crosses the pivot again. A range of zero or one values is sorted already, so the repetition must end.

5Watching one partition of 7, 2, 1, 6, 8, 5, 3, 4

The picture follows the code's real run, with new Random(42) as in the solution. Cells before store are the values already known to be smaller than the pivot, the cell under j is the one being tested, and the pivot waits at the end. The panel shows the pivot, store and the test made at each step.

Watch store. It only moves when a smaller value is found, and the values between store and j are the ones that were not smaller.

Step throughOne partition of 7, 2, 1, 6, 8, 5, 3, 4

Cells before store hold values smaller than the pivot; the cell under j is being tested; the pivot waits at the end. This is the run with new Random(42).

  1. 7021126384553647
    lo..hi
    0..7
    random index
    5
    pivot
    5

    1The first random choice for indexes 0 to 7 is index 5, so the pivot is 5. It is about to be swapped to the end.

  2. 7021126384453657store
    pivot
    5
    store
    0

    2After the swap, 5 sits at index 7 and 4 has moved to index 5. store starts at 0: no smaller values have been placed yet.

  3. 7021126384453657jstore
    pivot
    5
    store
    0
    a[j] < pivot
    7 < 5 no

    3j = 0 tests 7. It is not smaller than 5, so nothing moves and store stays at 0.

  4. 2071126384453657jstore
    pivot
    5
    store
    1
    a[j] < pivot
    2 < 5 yes

    4j = 1 tests 2, which is smaller. It is swapped into index store, 0, so 2 and 7 change places, and store moves to 1.

  5. 2011726384453657jstore
    pivot
    5
    store
    2
    a[j] < pivot
    1 < 5 yes

    5j = 2 tests 1, also smaller. It is swapped into index 1, the 7 moves along to index 2, and store moves to 2.

  6. 2011726384453657jstore
    pivot
    5
    store
    2
    a[j] < pivot
    6, 8 no

    6j = 3 and j = 4 test 6 and 8. Neither is smaller than 5, so nothing moves and store stays at 2.

  7. 2011426384753657jstore
    pivot
    5
    store
    3
    a[j] < pivot
    4 < 5 yes

    7j = 5 tests 4, which is smaller. It is swapped with the 7 at index store, 2, and store moves to 3.

  8. 2011423384756657jstore
    pivot
    5
    store
    4
    a[j] < pivot
    3 < 5 yes

    8j = 6 tests 3, which is smaller. It is swapped with the 6 at index 3, and store moves to 4. The scan is over.

  9. 2011423354756687store
    p returned
    4

    9The final swap exchanges the pivot with the 8 at index store, 4. Now 5 is in its final place, with 2 1 4 3 before it and 7 6 8 after it.

  10. 2011423354756687
    p - lo
    4
    hi - p
    3
    recurse into
    5..7

    10The left part, indexes 0 to 3, has four values and the right part, 5 to 7, has three. The code recurses into the smaller right part and loops on the left.

  11. 1021324354657687
    partitions
    5
    comparisons
    15

    11Four more partitions follow, with random pivots 7, 4, 3 and 2. Each puts one value in its final place, and the array ends as 1 2 3 4 5 6 7 8.

Let us read the important frames back. In the first two frames the random choice picks index 5, value 5, and the swap parks it at the end, which brings the 4 forward to index 5. At j = 0 the 7 is not smaller, so it stays and store waits at 0. At j = 1 the 2 is smaller, so it swaps with the 7, and store moves on. Notice the 7 is carried along each time a smaller value is found, always sitting just at store.

At j = 5 and j = 6 the values 4 and 3 are swapped to the front, so after the scan the array reads 2 1 4 3 8 7 6 with the 5 at the end. The final swap exchanges the 5 with the 8 at store, and the 5 is finished: smaller values on its left, larger on its right.

The tenth frame shows the choice about recursion. The left part, indexes 0 to 3, has four values and the right part has three, so the code recurses into the right part and loops on the left. The last frame shows the end of the whole sort after four more partitions.

6The complete Java program

Here is the full program, with a public quickSort method, the sort loop that recurses into the smaller side, the partition and a swap helper. main sorts the example, an array with duplicates and negatives, an empty array, and 100,000 values that are already sorted, which a first-value pivot would handle in quadratic time.

Java
import java.util.*;
public class QuickSort {
private static final Random RANDOM = new Random(42);
static void quickSort(int[] a) {
sort(a, 0, a.length - 1);
}
// Sorts a[lo..hi]. Recurse into the smaller side and loop on the larger, so the stack stays O(log n).
static void sort(int[] a, int lo, int hi) {
while (lo < hi) {
int p = partition(a, lo, hi);
if (p - lo < hi - p) {
sort(a, lo, p - 1);
lo = p + 1;
} else {
sort(a, p + 1, hi);
hi = p - 1;
}
}
}
// Lomuto partition around a random pivot; returns the pivot's final index.
static int partition(int[] a, int lo, int hi) {
swap(a, lo + RANDOM.nextInt(hi - lo + 1), hi); // random pivot, moved to the end
int pivot = a[hi];
int store = lo; // a[lo..store-1] holds values < pivot
for (int j = lo; j < hi; j++) {
if (a[j] < pivot) swap(a, store++, j);
}
swap(a, store, hi); // pivot lands between the two parts
return store;
}
static void swap(int[] a, int i, int j) {
int t = a[i]; a[i] = a[j]; a[j] = t;
}
public static void main(String[] args) {
int[] a = {7, 2, 1, 6, 8, 5, 3, 4};
quickSort(a);
System.out.println(Arrays.toString(a)); // [1, 2, 3, 4, 5, 6, 7, 8]
int[] b = {3, -1, 3, 0, -1, 3};
quickSort(b);
System.out.println(Arrays.toString(b)); // [-1, -1, 0, 3, 3, 3]
int[] c = {};
quickSort(c);
System.out.println(Arrays.toString(c)); // []
int[] sorted = new int[100_000];
for (int i = 0; i < sorted.length; i++) sorted[i] = i;
quickSort(sorted); // sorted input: random pivots keep this fast
System.out.println(sorted[99_999]); // 99999
}
}

Let us read it in the order it runs. quickSort simply calls sort on the whole range, from 0 to a.length - 1. In sort, the while loop runs as long as the range holds at least two values, lo < hi. It calls partition, which returns p, the pivot's final index.

Inside partition, the first line picks a random index with lo + RANDOM.nextInt(hi - lo + 1), a number from lo to hi inclusive, and swaps it to hi. Then pivot remembers the value, store starts at lo, and the for loop runs j from lo up to hi - 1, swapping each smaller value into store and moving store on. The last swap puts the pivot at store, and we return store.

Back in sort, we compare the sizes of the two parts. If the left part, p - lo values, is smaller than the right part, hi - p values, we recurse into the left with sort(a, lo, p - 1) and then set lo = p + 1, so the loop carries on with the right part. Otherwise we recurse into the right and set hi = p - 1. The loop ends when the remaining range has fewer than two values.

The condition a[j] < pivot sends values equal to the pivot to the right side. That is correct, as the duplicate test in main shows, but an array of many equal values still splits unevenly, which the first follow-up question below deals with.

The mistake beginners make most often is including the pivot in one of the parts, writing sort(a, lo, p) instead of sort(a, lo, p - 1). It looks harmless, but if the pivot is the largest value, p equals hi, and the call receives exactly the same range again, forever, until the stack overflows. The pivot is finished, so both parts must leave it out.

7How much it costs, and the cases at the edges

Let us count on the example first. The run made five partitions, of 8, 3, 4, 3 and 2 values, with 7, 2, 3, 2 and 1 comparisons, 15 in all. n log2 n for n = 8 is 24, so the count sits comfortably inside that. In general each level of partitions touches each value about once, and with random pivots there are O(log n) levels on average, so the expected time is O(n log n).

The worst case, a bad pivot at every step, is still O(n^2), but with random pivots its chance is so small that it does not happen in practice. The sort is in place, and recursing into the smaller side keeps the call stack at O(log n) even then; on our example the calls never went more than three deep.

Comparing the ways to sort
ApproachTimeExtra space
Selection sortO(n^2) alwaysO(1)
Copying quick sort, first-value pivotO(n log n) average, O(n^2) on sorted inputO(n) per level
In place, random pivot, smaller side firstO(n log n) expectedO(log n) stack

The edge cases need no special code. An empty array or a single value never enters the loop, because lo is not less than hi. Negative values need nothing special. Already sorted and reverse sorted arrays are fast, because the pivot is random, which is why main can sort 100,000 sorted values at once. The weak spot that remains is an array where most values are equal, since every copy of the pivot goes to the same side; a three-way partition fixes it.

A small check is worth doing aloud in an interview. Trace one partition on a tiny array and confirm that every value before p is smaller than a[p] and every value after it is at least a[p].

8Follow-up questions

How do you handle many duplicate values?

We use a three-way partition, often called the Dutch national flag scheme. Instead of two groups, we keep three: values less than the pivot, values equal to it, and values greater, with one index for the end of the less group, one for the start of the greater group, and one walking between them. Then we recurse only into the less and greater groups. Every copy of the pivot is finished in that one pass, so an array where every value is the same sorts in O(n) instead of O(n^2).

What is the difference between the Lomuto and Hoare partitions?

Lomuto, which we used, walks one index from left to right and is the easiest to write correctly. Hoare's scheme moves two indexes towards each other from both ends and swaps a pair whenever both are on the wrong side. It does about three times fewer swaps on average and copes better with duplicates, but the pivot does not necessarily end at the returned index, so the two recursive ranges are slightly different and easy to get wrong under pressure.

How do you find the k-th smallest value with the same partition?

That is quickselect. After one partition, the pivot's index p tells us exactly how many values are smaller than it. If p equals k, the pivot is the answer. If k is smaller, the answer lies in the left part, and otherwise in the right part, so we continue in only that one part. Because we follow one side instead of two, the work shrinks quickly, and the expected time is O(n) rather than O(n log n).

9Conclusion

We wrote quick sort in place. A random pivot is swapped to the end, the Lomuto partition sweeps the smaller values to the front behind a store index, the pivot is swapped into its final place, and the smaller part is sorted by recursion while the larger part is handled by the loop. That gives O(n log n) expected time and O(log n) stack with no extra arrays, while the copying version uses O(n) memory per level and a first-value pivot is quadratic on sorted input. The clue to remember: splitting an array into groups in place is a partition, and quick sort is a partition applied again and again.

What to say in the interviewAbout 80 seconds aloud

Open with

I will sort an int array in place, with duplicates and negatives possible, and the input may already be sorted, so I will not use the first value as the pivot.

Then, if they want more

Selection sort is a correct baseline but n squared. A quick sort that copies into less, equal and greater lists is easy to write, but it uses linear extra memory per level, and with a first-value pivot it is quadratic on sorted input. So I partition in place with the Lomuto scheme.

I pick a random index in the range and swap it to the end as the pivot. I keep a store index, and everything before store is smaller than the pivot. I scan j from lo to hi minus one, and whenever a of j is smaller, I swap it into store and move store on.

At the end I swap the pivot into store, which is its final position. Then I sort the two sides, recursing into the smaller one and looping on the larger, so the stack stays at log n. Random pivots make the expected time O(n log n).

Empty and single-value arrays return at once, and for many duplicates I would use a three-way partition.

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
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 "Write an implementation of quick sort.": https://scrivio-interview-library.netlify.app/data-structures/solutions/write-an-implementation-of-quick-sort-243039/