Quick Sort is the sorting algorithm you'll meet most often in the real world. Like Merge Sort, it divides and conquers, but it does the hard work before splitting instead of after, and it sorts in place, without Merge Sort's extra array.
On average, it is one of the fastest sorting algorithms there is. But it has a weakness, and you'll see it happen in our very own example.
By the end of this lesson, you will understand:
- What a pivot is and how partitioning works
- How Quick Sort uses recursion
- How to trace it and write it in code
- Why it is usually
O(n log n), but can beO(n²) - How to avoid its worst case
What Is Quick Sort?
Quick Sort works like this:
- Pick a pivot. We'll use the last value of the range.
- Partition. Rearrange the range so that every value not bigger than the pivot is on its left, and every bigger value is on its right.
- The pivot is now in its final place. It never moves again.
- Repeat for the left side and the right side, separately.
A range with one value, or none, is already sorted, so the repeating stops there.
Watch it below. The blue band shows the range being partitioned, pivot marks the pivot, and i marks the end of the "not bigger than the pivot" side. Each pivot turns green as it lands in its final place.
The Picking Teams Analogy
A sports teacher wants students ordered by height, without measuring everyone against everyone.
1. Choose One Student
The teacher picks one student as the pivot.
2. Shorter Left, Taller Right
Everyone shorter (or the same height) moves to the pivot's left. Everyone taller moves to the right. The two groups aren't sorted yet, they're just on the correct side.
3. The Pivot Is Settled
The pivot is now standing exactly where they belong in the final line.
4. Repeat in Each Group
The teacher does the same thing within the left group, and within the right group, until every group has just one student.
How Partitioning Works
Partitioning walks through the range once, with two markers:
jlooks at each value in turn.imarks the end of the left side, the values found so far that are not bigger than the pivot.
When j finds a value that is not bigger than the pivot, i moves forward one place and the two values swap, pulling that value into the left side. At the end, the pivot swaps into the spot just after the left side.
Tracing It by Hand
Let's sort [5, 1, 4, 2, 8].
Partition 1: [5, 1, 4, 2, 8], pivot 8
| Compare with pivot 8 | Result |
|---|---|
| 5 | not bigger: left side |
| 1 | not bigger: left side |
| 4 | not bigger: left side |
| 2 | not bigger: left side |
Every value is smaller than 8, so they were all already on the left, and nothing moves. 8 is in its final place, at the end. But look what happened: the left side has 4 values and the right side has none. 8 was a bad pivot. We'll come back to this.
Partition 2: [5, 1, 4, 2], pivot 2
| Compare with pivot 2 | Result | Array after |
|---|---|---|
| 5 | bigger: stays right | [5, 1, 4, 2] |
| 1 | not bigger: swap 1 and 5 | [1, 5, 4, 2] |
| 4 | bigger: stays right | [1, 5, 4, 2] |
Now swap the pivot 2 into the spot after the left side: [1, 2, 4, 5]. 2 is in its final place, with [1] on its left and [4, 5] on its right.
Partition 3: [4, 5], pivot 5
| Compare with pivot 5 | Result |
|---|---|
| 4 | not bigger: left side |
5 is already in its final place. [1] and [4] are single values, so they're done.
The result is [1, 2, 4, 5, 8], in 8 comparisons and 2 swaps that actually moved something. The code below also "swaps" a value with itself whenever i and j point to the same place. That changes nothing, so the animation doesn't count it.
Quick Sort in Code
This version is called the Lomuto partition scheme, and it is the one most textbooks teach first.
import java.util.Arrays;
public class Main {
static void quickSort(int[] a, int low, int high) {
if (low < high) {
int p = partition(a, low, high); // the pivot lands in its final place, p
quickSort(a, low, p - 1); // sort the values left of the pivot
quickSort(a, p + 1, high); // sort the values right of the pivot
}
}
static int partition(int[] a, int low, int high) {
int pivot = a[high]; // use the last value as the pivot
int i = low - 1; // end of the "not bigger" side
for (int j = low; j < high; j++) {
if (a[j] <= pivot) { // belongs on the left side
i++;
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
int temp = a[i + 1]; // put the pivot just after the left side
a[i + 1] = a[high];
a[high] = temp;
return i + 1;
}
public static void main(String[] args) {
int[] marks = {5, 1, 4, 2, 8};
quickSort(marks, 0, marks.length - 1);
System.out.println(Arrays.toString(marks)); // [1, 2, 4, 5, 8]
}
}Let's connect the code to the trace:
partitiondoes the real work. It returnsp, the pivot's final position.istarts atlow - 1, meaning "the left side is empty so far".- The loop stops before
high, becausehighis the pivot itself. - After the loop, the pivot swaps into
i + 1, the first spot after the left side. quickSortthen sortslowtop - 1andp + 1tohigh, skippingp, because the pivot is already settled.
How Fast Is Quick Sort?
| Case | Example | Time | Why |
|---|---|---|---|
| Best | Pivot always lands in the middle | O(n log n) | Each split halves the range, like Merge Sort |
| Average | Random order | O(n log n) | Splits are usually reasonably balanced |
| Worst | Already sorted, or reversed | O(n²) | The pivot is always the largest or smallest, so each split removes just one value |
| Extra memory | Any | O(log n) on average | Only the recursion; the array is sorted in place |
Remember Partition 1 in our trace, where pivot 8 left nothing on its right? That is what goes wrong in the worst case. If every pivot is the largest (or smallest) value, each partition only settles one value, and you get n(n − 1) / 2 comparisons, just like Bubble Sort.
With the last value as pivot, that happens on already sorted data. Try it in the animation: Sorted and Reversed both take all 21 comparisons, while Random usually needs far fewer.
Avoiding the Worst Case
The fix is to choose the pivot more carefully:
- Random pivot: pick a random value in the range and swap it to the end before partitioning. A bad split every time then becomes extremely unlikely.
- Median of three: look at the first, middle and last values, and use the middle one of those three as the pivot.
Real libraries go further. Many use Introsort, which starts with Quick Sort and switches to a different algorithm if the recursion goes too deep.
Quick Sort is not stable. Partitioning swaps values over long distances, so equal values can end up in a different order.
Common Mistakes
1. Letting the Loop Reach the Pivot
The loop must be j < high, not j <= high. Including high compares the pivot with itself and swaps it into the left side too early.
2. Forgetting the Final Pivot Swap
Without swap(a[i + 1], a[high]), the pivot stays at the end instead of moving to its final place, and partition returns the wrong position.
3. Recursing on the Pivot Again
Recursing on low to p instead of low to p - 1 keeps including the pivot. When the pivot is the largest value in a range, that range never gets smaller, so the recursion never stops.
When Should You Use Quick Sort?
Good for:
- Large arrays in general: it is usually the fastest in practice
- When memory is tight: it sorts in place
Not good for:
- Sorts that must be stable: use Merge Sort
- When you need a guaranteed
O(n log n): use Merge Sort, or a careful pivot choice - Data that may already be sorted, if you use a simple last-value pivot
In the next lesson, we will learn our last sorting algorithm, Heap Sort. Like Quick Sort it sorts in place, but it has no bad worst case.
Remember This
If you remember only one thing from this lesson, remember: Quick Sort picks a pivot, moves smaller values to its left and bigger ones to its right, then sorts each side. It is O(n log n) on average and sorts in place, but a bad pivot makes it O(n²).