DSA · Patterns, not puzzles
How does quicksort work?
Short answer
Quicksort chooses a pivot, partitions the array so smaller elements are on one side, then recursively sorts both sides. It is in-place with O(n log n) average time but O(n^2) worst case.
Quicksort's performance depends almost entirely on pivot choice. A balanced split gives log n levels; a consistently bad split gives n levels. Randomised pivots or median-of-three reduce the chance of hitting the worst case on real input.
function quicksort(values, low = 0, high = values.length - 1) {
if (low >= high) return values;
const pivotIndex = partition(values, low, high);
quicksort(values, low, pivotIndex - 1);
quicksort(values, pivotIndex + 1, high);
return values;
}
function partition(values, low, high) {
const pivot = values[high];
let smaller = low;
for (let i = low; i < high; i++) {
if (values[i] < pivot) {
[values[i], values[smaller]] = [values[smaller], values[i]];
smaller += 1;
}
}
[values[smaller], values[high]] = [values[high], values[smaller]];
return smaller;
}Why the worst case happens
- Choosing the last element as pivot on already sorted input gives O(n^2)
- Each partition removes only one element in the worst case
- Randomised or median pivots make the bad case unlikely
- Recursion depth is O(log n) average and O(n) worst
- Quicksort is not stable
Quicksort is usually faster than merge sort in practice because it sorts in place and has good cache behaviour. Merge sort has the safer worst-case guarantee. In languages with a built-in sort, the implementation is often a hybrid that switches to insertion sort for small ranges.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why is quicksort O(n^2) on sorted input with a last-element pivot?
- 2How do you avoid the worst case?
- 3Why is quicksort not stable?
- 4When would you choose merge sort instead?
Say it in the interview
Quicksort picks a pivot, partitions smaller elements to one side and larger to the other, then recurses on both sides. The pivot ends in its final position. Average time is O(n log n) and it sorts in place, but a bad pivot can make it quadratic. I would randomise the pivot or use median-of-three to make that unlikely, and I would choose merge sort when I need a guaranteed bound or stability.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live DSA mock interview and get scored feedback on depth, clarity and confidence.