Quick Sort
Idea Like You Are 10
Pick one number and call it the pivot.
Now split everything into:
- numbers smaller than the pivot
- the pivot
- numbers bigger than the pivot
Then do the same thing again for the left part and the right part.
This is called divide and conquer.
Small Example
Sort:
Pick pivot = 5
Split:
Now sort the smaller part:
Pick pivot = 3
Now combine:
Diagram
Algorithm
- Choose a pivot
- Put smaller elements on one side
- Put bigger elements on the other side
- Recursively sort both sides
Pseudocode
Time Complexity
| Case | Time |
|---|---|
| Best | O(n log n) |
| Average | O(n log n) |
| Worst | O(n^2) |
Why This Time Complexity?
Best And Average Case: O(n log n)
If the pivot splits the array into two fairly equal parts:
- there are about
log nlevels - each level processes about
nelements
So:
Worst Case: O(n^2)
If the pivot is always terrible, like always the smallest or largest item, the split becomes very uneven.
Example:
If we always choose the first or last element as pivot, we get:
That becomes O(n^2).
Space Complexity
- Usually
O(log n)extra stack space because of recursion - In the worst case, recursion stack can become
O(n)
Performance
- Usually one of the fastest in real programs
- Very popular
- Can become slow with bad pivot choices
When To Use
- Large arrays
- General-purpose fast sorting
- When average speed matters a lot