What is Sorting and how to compare algorithms?
Solution and explanation
What it is
Sorting arranges elements in a defined order (ascending, descending or by a key such as salary or date). Sorted data makes searching (binary search), de-duplication, grouping and merging much faster.
Comparing sorting algorithms
- Time complexity (best, average, worst).
- Space: in-place (O(1) extra) or not.
- Stability: a stable sort keeps equal elements in their original order (important when sorting records by a second key).
- Adaptivity: does it run faster on nearly sorted data?
Summary table
- Bubble sort: O(n²) average/worst, O(n) best (with early exit), O(1) space, stable.
- Selection sort: O(n²) always, O(1) space, not stable, minimum number of swaps.
- Insertion sort: O(n²) worst, O(n) best on nearly sorted data, O(1) space, stable.
- Merge sort: O(n log n) always, O(n) space, stable.
- Quick sort: O(n log n) average, O(n²) worst, O(log n) stack space, not stable.
- Heap sort: O(n log n) always, O(1) space, not stable.
- Counting/radix sort: O(n + k) for small integer ranges, not comparison based.
What Java uses
- Arrays.sort on primitives: dual-pivot quicksort.
- Arrays.sort on objects and Collections.sort: TimSort (merge + insertion sort), stable, O(n log n), very fast on partly sorted data.
int[] scores = {72, 15, 90, 41};
Arrays.sort(scores); // [15, 41, 72, 90]
List<Employee> staff = new ArrayList<>(...);
staff.sort(Comparator.comparing(Employee::department)
.thenComparing(Employee::salary, Comparator.reverseOrder()));
Lower bound
Any comparison-based sort needs Ω(n log n) comparisons in the worst case, so merge, heap and quick sort are optimal in that model.
Note: in interviews, state stability and space alongside time complexity when you choose a sort.
