Quick Sort
- Ω( n log n )
- Θ( n log n )
- O( n2 )
- space O( log n )
This quick sort takes the median of the first, middle and last element as its pivot, partitions the range with Lomuto's single left-to-right scan, and always recurses into the smaller side first. It works in place, allocates no second array and does not keep equal elements in their original order. The trace below follows one real run on six numbers.
- Comparisons count only element-against-element checks; loop and index checks are never counted.
- Reads and writes include reads and writes to helper buffers (merge, counting, radix, bucket and tim sort).
- A swap counts once, as a swap. It is never also counted as a read or a write.
- Real time is the average time of the counted sort on this device over repeated runs, measured once before playback and independent of animation speed. Visual time is the time spent animating, excluding pauses.
How quick sort works
The first call looks at positions 0, 2 and 5 of 5, 2, 6, 1, 4, 3, which hold 5, 6 and 3. Two swaps put them in order and give 3, 2, 5, 1, 4, 6, so the median, 5, sits in the middle. The code then swaps the median into the last slot, producing 3, 2, 6, 1, 4, 5. Those are the first three rows of the table, and no element has been partitioned yet. The pivot is 5.
Now a single scan runs from left to right, keeping a boundary behind which everything is smaller than 5. The 3 and the 2 are already on the correct side, so they cost comparisons but no swaps. The 6 is skipped. The 1 is smaller than the pivot and trades places with the 6, giving 3, 2, 1, 6, 4, 5, and the 4 does the same, giving 3, 2, 1, 4, 6, 5. A last swap drops the pivot onto the boundary: 3, 2, 1, 4, 5, 6. The 5 is now in its final slot, index 4.
The remaining work is the left part, 3, 2, 1, 4. Its median-of-three step swaps 3 and 2 to give 2, 3, 1, 4, 5, 6, and the partition around 3 ends at 2, 1, 3, 4, 5, 6. That leaves the pair 2, 1, which the table shows as swap 1,0 followed by swap 0,1 twice. The array is fully sorted after the eleventh swap, yet the last two swaps first move the median into the pivot slot, which unsorts the pair, and then partition it back. Six elements cost 18 comparisons and 13 swaps; the median-of-three setup only pays for itself on larger inputs.
| Step | Change | Array after |
|---|---|---|
| 1 | Swap indexes 5 and 0 | 3 2 6 1 4 5 |
| 2 | Swap indexes 5 and 2 | 3 2 5 1 4 6 |
| 3 | Swap indexes 2 and 5 | 3 2 6 1 4 5 |
| 4 | Swap indexes 2 and 3 | 3 2 1 6 4 5 |
| 5 | Swap indexes 3 and 4 | 3 2 1 4 6 5 |
| 6 | Swap indexes 4 and 5 | 3 2 1 4 5 6 |
| 7 | Swap indexes 1 and 0 | 2 3 1 4 5 6 |
| 8 | Swap indexes 1 and 3 | 2 4 1 3 5 6 |
| 9 | Swap indexes 1 and 2 | 2 1 4 3 5 6 |
| 10 | Swap indexes 2 and 3 | 2 1 3 4 5 6 |
| 11 | Swap indexes 1 and 0 | 1 2 3 4 5 6 |
| 12 | Swap indexes 0 and 1 | 2 1 3 4 5 6 |
12 of 13 changes shown; the rest follow the same pattern until the array is sorted.
Pseudocode
quicksort(lo, hi)
while lo < hi
order a[lo], a[mid], a[hi]
swap the median a[mid] with a[hi]
pivot = a[hi]
i = lo - 1
for j = lo to hi - 1
if a[j] < pivot
i = i + 1
swap a[i], a[j]
swap a[i + 1], a[hi]
p = i + 1
recurse into the smaller of lo..p - 1 and p + 1..hi
loop on the larger
Why these complexities
Each partition reads every element of its range once and compares it with the pivot, so one level of recursion costs about n comparisons. When the pivot splits the range reasonably evenly, there are about log₂ n levels, which gives O(n log n). The split does not have to be perfect: even a 90 to 10 split only changes the constant. On 1000 shuffled values this version made 11,650 comparisons and 5,402 swaps.
The quadratic case needs pivots that keep landing near one end, so each call removes a single element and the total becomes n minus 1, plus n minus 2, and so on, about n²/2 comparisons. Median-of-three makes sorted and reversed input harmless; sorted input of 1000 took only 9,520 comparisons, fewer than the shuffled one. It does not stop every bad input. Carefully built sequences still defeat it, and so do many equal keys: the partition test is a strict less-than, so every element equal to the pivot is sent to the right side. An array of 1000 equal values peels off one element per call and costs 502,497 comparisons.
Extra memory is only the call stack. After partitioning, the code recurses into the smaller side and continues with the larger side in a loop, so every pending call covers at most half of the range above it. The stack therefore stays within about log₂ n frames, even on inputs where the running time is quadratic. The sort is not stable because the scan swaps an element with one far to its left, and it is not adaptive: even sorted input still costs about n log₂ n comparisons.
Measured on this site
Exact counts from this site's own engine for 32 elements, using the same rules as the visualiser.
| Input | Comparisons | Writes | Swaps |
|---|---|---|---|
| Random | 183 | 0 | 85 |
| Already sorted | 151 | 0 | 32 |
| Reversed | 177 | 0 | 94 |
| Few distinct values | 242 | 0 | 84 |
When to use it
Use it as a fast general-purpose sort for arrays in memory when you do not need stability. It sorts in place, and on average it is among the fastest comparison sorts. If a quadratic worst case is unacceptable, choose intro sort or merge sort.
Frequently asked questions
What is the worst case of quick sort?
O(n²), when every pivot lands near one end of its range. Taking the median of the first, middle and last element makes that unlikely for sorted and reversed input.
Is quick sort stable?
No. Partitioning swaps elements over long distances, so equal elements can change their order.
Why is quick sort fast in practice?
It works in place with sequential memory access, which suits the cache, and its inner loop is very short.
What happens when every element is equal?
It degrades to quadratic time. The partition uses a strict less-than test, so no element is smaller than the pivot and every call splits the range into an empty part and a part with one element fewer. A thousand equal values cost 502,497 comparisons, against 11,650 for a shuffled thousand. Three-way quick sort exists for this situation.
Why does it recurse into the smaller side first?
To bound the stack. Recursing into the smaller part and looping over the larger part means each pending call is at most half the size of the one above it, so the depth cannot exceed about log₂ n. Without that rule a bad run of pivots could nest about n calls deep and overflow the stack on a large array.
Background
Tony Hoare devised quick sort in 1959, while working on machine translation, and published the algorithm in 1961 and a fuller analysis in 1962. His partition moved two indices towards each other from both ends. The version in this visualiser uses the simpler one-directional scheme usually credited to Nico Lomuto, which was popularised by Jon Bentley's Programming Pearls and by the Cormen, Leiserson, Rivest and Stein textbook. It is easy to get right, at the price of more swaps.
The pivot rule matters as much as the partition. Choosing the median of three sampled elements has been standard practice since the 1970s, and Robert Sedgewick's 1978 paper collected the practical refinements, such as switching to insertion sort for tiny ranges, that turned the textbook algorithm into a library routine. Intro sort and dual-pivot quick sort are later descendants of that line of work.
References
- Hoare, Quicksort, The Computer Journal 5(1), 1962
- Knuth, The Art of Computer Programming, vol. 3, section 5.2.2
- Sedgewick, Implementing Quicksort Programs, Communications of the ACM 21(10), 1978
- Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms, chapter 7
Compare with
| Algorithm | Average time | Worst time |
|---|---|---|
| Bubble Sort | Θ( n2 ) | O( n2 ) |
| Cocktail Shaker Sort | Θ( n2 ) | O( n2 ) |
| Comb Sort | Θ( n2 ) | O( n2 ) |
| Gnome Sort | Θ( n2 ) | O( n2 ) |
| Odd-Even Sort | Θ( n2 ) | O( n2 ) |
| 3-Way Quick Sort | Θ( n log n ) | O( n2 ) |
| Dual-Pivot Quick Sort | Θ( n log n ) | O( n2 ) |
| Best time | Ω( n log n ) | good |
|---|---|---|
| Average time | Θ( n log n ) | good |
| Worst time | O( n2 ) | poor |
| Worst space | O( log n ) | good |
Properties
- Stable
- No
- In place
- Yes
- Adaptive
- No
- Comparison-based
- Yes