Quick Sort, explained step by step
Quick Sort is a Divide and Conquer algorithm. It picks an element as a pivot and partitions the given array around the picked pivot. By placing the pivot in its exact correct sorted position and organizing smaller elements to its left and larger elements to its right, it effectively breaks the sorting problem into two smaller sub-problems.
Intuition: Pick a person in the line (pivot). Ask everyone shorter to stand on their left and everyone taller on their right. Now the pivot is in the exact right spot. Repeat for the left and right groups.
How it works
- Pick an element as pivot (we use the last element).
- Partition the array by moving elements smaller than the pivot to the left, and larger elements to the right.
- Place the pivot in its correct sorted position.
- Recursively apply the same logic to the left and right sub-arrays.
Complexity
- Best: O(n log n)
- Average: O(n log n)
- Worst: O(n²)
- Space: O(log n)
- Stable: no
When to use it
General-purpose sorting. Fast in practice due to excellent cache locality. Default algorithm used in many language libraries (often hybridised as Introsort).
Interview questions
- What is the worst-case time complexity of Quick Sort, and when does it occur?
- How can you mitigate the O(n²) worst-case scenario in Quick Sort?
- Why is Quick Sort generally preferred over Merge Sort for arrays?