Sorting: Comparators, Merge Sort and Quick Sort
Sorting is a building block for many solutions. In Java you'll use Arrays.sort and Comparators daily; knowing merge sort and quick sort helps you understand performance and answer interview questions.
Sorting with the Java library
Example
Arrays.sort and Collections.sort are O(n log n). For objects Java uses TimSort, which is stable (equal items keep their order).
Merge sort
Example
Quick sort
Example
- Merge sort - always O(n log n), stable, needs extra memory
- Quick sort - O(n log n) on average, O(n²) in the worst case, sorts in place
- Bubble / selection / insertion - O(n²); fine for tiny arrays and for learning
Key points
- Comparator.comparing builds custom sort orders.
- Merge sort is stable and always O(n log n).
- Quick sort is in-place, O(n log n) on average.
📝 Test yourself
1. Which is always O(n log n)?
2. What does a stable sort keep?
3. Fill in the method that reverses a Comparator:
Comparator.comparingInt(...).()
