COMPARISON SORTS
Quick Sort, visualised
Quick sort picks a pivot, moves smaller elements to its left and the rest to its right, and then sorts each side recursively.
Run Quick Sort in the visualizer →
Opens the Sorting Cinema visualizer with 16 elements in English.
How it works
- Choose the last element of the range as the pivot (this app's implementation).
- Compare each element with the pivot from the left and swap smaller ones into the left part.
- Finally swap the pivot right after the smaller elements; its final position is now fixed.
- Sort the parts left and right of the pivot in the same way.
Complexity and stability
- Best
- O(n log n)
- Average
- O(n log n)
- Worst
- O(n²)
- Extra space
- O(log n) average, O(n) worst
- Stability
- Usually unstable
Balanced partitions give O(n log n), but unbalanced partitions degrade to a worst case of O(n²). Extra space is the recursion stack: O(log n) on average, O(n) in the worst case.
Source of facts: Complexity follows the learning guide's comparison table and text, and this app's implementation.
Trace on a small array
The first operations on the input [5, 2, 4, 1, 3], following the same steps as the app.
| # | Operation | Array after |
|---|---|---|
| 1 | Compare [0]=5 and [4]=3 | [5, 2, 4, 1, 3] |
| 2 | Compare [1]=2 and [4]=3 | [5, 2, 4, 1, 3] |
| 3 | Swap [0]=5 and [1]=2 | [2, 5, 4, 1, 3] |
| 4 | Compare [2]=4 and [4]=3 | [2, 5, 4, 1, 3] |
| 5 | Compare [3]=1 and [4]=3 | [2, 5, 4, 1, 3] |
| 6 | Swap [1]=5 and [3]=1 | [2, 1, 4, 5, 3] |
| 7 | Swap [2]=4 and [4]=3 | [2, 1, 3, 5, 4] |
| 8 | Compare [0]=2 and [1]=1 | [2, 1, 3, 5, 4] |
…and so on. In this trace, 11 compare / swap / write operations in total produce [1, 2, 3, 4, 5].
Suitable inputs and caveats
- This app uses the last element as the pivot, so sorted, reversed and many-duplicates inputs can produce unbalanced partitions.
- On random input you can easily follow the pivot landing in its final position.
- It swaps distant elements, so it is usually unstable.
FAQ
Why is quick sort's worst case O(n²)?
If the pivot is always the smallest or largest value, one side of the partition is empty and the range shrinks by only one each time. With this app's last-element pivot, sorted input can trigger this.
Should I use quick sort or merge sort?
Both average O(n log n). Merge sort guarantees the worst case and stability; quick sort uses less extra space. Judge real speed with a controlled benchmark.