How Quicksort works
The basic idea of Quicksort is to repeatedly divide the array into smaller
pieces (these are called partitions), and to recursively sort those partititons.
Quicksort divides the current partition by choosing an element - the pivot - finding which
of the other elements are smaller or larger, sorting them into two different
sub-partitions (one for the values smaller than the pivot, one for those larger
than the pivot). For example, say we have the input (5,7,2,3,1,4,6).
Here's what happens in the first partitioning run of a standard Quicksort
algorithm (one that always chooses the middle element of the current partition as
the pivot):
Data | Comments |
5 | 7 |
2 | 3 |
1 | 4 |
6 |
3 | 7 | 2 | 5 | 1 |
4 | 6 |
3 | 7 | 2 | 5 | 1 |
4 | 6 |
3 | 1 | 2 | 5 | 7 |
4 | 6 |
3 | 1 | 2 | 5 | 7 |
4 | 6 |
2 | 1 | 3 | 5 | 7 |
4 | 6 |
2 | 1 | 3 | 5 | 7 |
4 | 6 |
1 | 2 | 3 | 5 | 7 |
4 | 6 |
1 | 2 | 3 | 4 | 5 |
6 | 7 |