Quicksort
Overview
-
Quicksort uses
Divide and Conquerto recursively sort an array of elements -
Pick a
pivot, put smaller elements on the left, larger elements on the right (this is calledpartitioning) -
Recursively sort the two smaller sub-arrays
-
Average case
O(n log n), worst caseO(n^2)
Base Cases
These arrays are really easy to sort:
[]: Empty Array, already sorted[5]: Single Element, already sorted
Two elements are a tiny bit harder, but still easy:
[3, 7]: left < right, already sorted[7, 3]: left > right, just swap the elements
Recursive Cases
- Pick an element to be the
Pivot - Move elements
less thanthe pivot to theleftsub-array - Move elements
greater thanthe pivot to therightsub-array - Recursively call quicksort on the sub-arrays, return to step (1)
Quicksort Complexity
Quicksort is a little strange, the complexity depends on which pivot we choose.
We get the best performance when we pick the pivot completely randomly every time.
-
Average Case:
O(n logn) -
Worst Case:
O(n^2)
Notes
Quicksortis actually faster thanMerge Sort, even though they have the same complexityO(n logn)