QuickSort in Java
Learn how QuickSort works: its time and space complexity, the algorithm in pseudo code, and a step-by-step visualisation that follows the Java code line by line.
Introduction
QuickSort is a divide-and-conquer sorting algorithm. It picks one element as the pivot, rearranges the array so that smaller values end up on the left and larger values on the right, and then sorts both parts the same way, recursively.
Three ideas carry the whole algorithm:
- Pivot: the value every other element is compared against.
- Pointers: two indices,
leftandright, that walk toward each other looking for elements on the wrong side. - Swap: when both pointers have found a misplaced element, the two values trade places.
QuickSort sorts in place (no second array is needed) and is, in practice, one of the fastest general-purpose comparison sorts. This is why variants of it are used in many standard libraries; Java’s Arrays.sort() uses a dual-pivot QuickSort for primitive arrays.
This article uses a Hoare-style partition with a middle pivot: the pointers start at both ends and move inward until they cross.
Performance Characteristics
QuickSort is one of the fastest general-purpose sorting algorithms in practice, but how fast it runs and how much memory it needs depend on how well each pivot splits the array.
Time Complexity
Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.
| Case | Time | When it happens |
|---|---|---|
| Best | $O(n \log n)$ | Every pivot splits the range into two roughly equal halves |
| Average | $O(n \log n)$ | Random or mixed input |
| Worst | $O(n^2)$ | Every pivot is the smallest or largest value of its range |
Why $n \log n$? Each partition level touches every element once ($n$ work), and halving the range each time gives about $\log_2 n$ levels.
Choosing the middle element as the pivot avoids the classic worst case of a pivot on the last element, where an already sorted array degrades to $O(n^2)$.
Space Complexity
Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.
| Property | Value |
|---|---|
| Space | $O(\log n)$ on average for the recursion stack, $O(n)$ worst case |
| In place | Yes |
| Stable | No (equal elements can change order) |
Algorithm (Pseudo Code)
QuickSort starts by picking the middle value of the array as the pivot. It then places a pointer at each end of the array. The left pointer moves right until it finds a value that is not smaller than the pivot, and the right pointer moves left until it finds a value that is not larger than the pivot. Both values are on the wrong side, so they swap places, and the pointers carry on.
When the pointers cross, the array is split in two: every value on the left is smaller than or equal to the pivot, and every value on the right is larger than or equal to it. QuickSort then repeats the same steps on each part. Each part gets smaller every time, and a part with one value is already sorted, so in the end the whole array is in order.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
quickSort(array, left, right):
if left < right:
split = partition(array, left, right)
quickSort(array, left, split - 1)
quickSort(array, split, right)
partition(array, left, right):
pivot = array[(left + right) / 2] // middle element
while left <= right:
while array[left] < pivot: left = left + 1
while array[right] > pivot: right = right - 1
if left <= right:
swap(array[left], array[right])
left = left + 1
right = right - 1
return left // split index
After partition returns, everything in [left .. split - 1] is ≤ pivot and everything in [split .. right] is ≥ pivot.
In this Hoare-style scheme the pivot is not guaranteed to be in its final position after a partition. That is why the second recursive call starts at
split, notsplit + 1.
Visualization
The visualization below follows the Java code line by line, starting with the values 0 to 9 in shuffled order.
Each step shows the array, the pointers and the line of code that is running, with a short explanation of what just happened:
- Step through: use the arrows to move one step forward or back, or drag the slider to jump to any step.
- Play: press Play to run the steps automatically, and press it again to pause.
- Shuffle: press the shuffle button to start again with a new random order.
- Pointers: L is the
leftpointer and R is therightpointer. - Colours: the pivot value is amber, the two values being swapped are salmon, and sorted values turn green.
- Split: the gray bar marks the split index returned by
partition. - Random swap: tick Include random swap to see the
randomPartitionstep from the Java code.
Java Code
The implementation is a QuickSort class with one public method, sort, and three private methods: doSort handles the recursion, randomPartition swaps one random element, and partition does the pointer work. Two small helpers, swap and less, live in a separate SortUtils class.
The complete code is in the algorithm-examples repository on GitHub:
QuickSort.java, with the helpers inSortUtils.java.
sort
1
2
3
4
5
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
doSort(array, 0, array.length - 1);
return array;
}
sort is the entry point. It accepts an array of any Comparable type, such as Integer or String, and sorts the whole array in place by calling doSort on the full range, from index 0 to the last index. It returns the same array, now sorted.
doSort
1
2
3
4
5
6
7
private static <T extends Comparable<T>> void doSort(T[] array, final int left, final int right) {
if (left < right) {
final int pivot = randomPartition(array, left, right);
doSort(array, left, pivot - 1);
doSort(array, pivot, right);
}
}
doSort is the recursive part. When the range has fewer than two elements, there is nothing to sort and it stops. Otherwise it partitions the range, then sorts the left part [left .. pivot - 1] and the right part [pivot .. right] the same way.
Despite its name, pivot here holds the split index returned by partition, not the pivot value. The right part starts at the split index itself, not one past it, because a Hoare-style partition doesn’t guarantee the pivot is in its final position.
randomPartition
1
2
3
4
5
private static <T extends Comparable<T>> int randomPartition(T[] array, final int left, final int right) {
final int randomIndex = left + (int) (Math.random() * (right - left + 1));
SortUtils.swap(array, randomIndex, right);
return partition(array, left, right);
}
randomPartition picks a random index in the range, swaps that element to the right end, and then hands over to partition. The idea is to break up input that is already sorted or nearly sorted.
The random swap doesn’t choose the pivot:
partitionstill takes the middle element. The swap only moves one element, and the middle pivot already protects against sorted input. For a truly random pivot, computerandomIndexinsidepartitionand usearray[randomIndex]as the pivot instead ofarray[mid].
partition
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private static <T extends Comparable<T>> int partition(T[] array, int left, int right) {
final int mid = (left + right) >>> 1;
final T pivot = array[mid];
while (left <= right) {
while (SortUtils.less(array[left], pivot)) {
++left;
}
while (SortUtils.less(pivot, array[right])) {
--right;
}
if (left <= right) {
SortUtils.swap(array, left, right);
++left;
--right;
}
}
return left;
}
partition does the real work. It takes the middle element as the pivot, then moves left forward past values smaller than the pivot and right backward past values larger than it. When both stop, their values are on the wrong side, so they swap and both pointers step inward. When the pointers cross, left is the split index, and partition returns it.
Two details are worth noticing:
(left + right) >>> 1finds the middle with an unsigned shift, so it can’t overflow the way(left + right) / 2can for very large indices.- The inner loops use strict comparisons, so both pointers stop on values equal to the pivot. That keeps the split balanced when the array has many duplicates.
swap and less
1
2
3
4
5
6
7
8
9
10
11
static <T> void swap(T[] array, int i, int j) {
if (i != j) {
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
static <T extends Comparable<T>> boolean less(T a, T b) {
return a.compareTo(b) < 0;
}
These two helpers from SortUtils keep partition easy to read. swap exchanges two elements, and skips the work when both indices are the same. less returns true when a is smaller than b, using compareTo, so the algorithm works for any type that implements Comparable.
Running it
1
2
3
4
Integer[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
new QuickSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Create a QuickSort, pass it an array, and the same array comes back sorted. The array holds Integer, not int, because the method works with Comparable objects.
Summary
- QuickSort is a divide-and-conquer sort: pick a pivot, partition around it, then recurse on both parts.
- This implementation uses a middle pivot and two pointers that move toward each other and swap misplaced elements until they cross.
- The returned index is a split point, not the pivot’s final position, so the recursion covers
[left .. split - 1]and[split .. right]. - It runs in $O(n \log n)$ on average, $O(n^2)$ in the worst case, and needs only $O(\log n)$ extra space on average.
- It sorts in place but is not stable. When you need stability (for example, when sorting objects by more than one key), use a merge sort instead; that’s what Java’s
Arrays.sort()does for object arrays.