Junior — Middle
Can you list the sorting algorithms used in Java and briefly describe their features?
sobes.tech AI
Answer from AI
In Java, different algorithms are used for sorting arrays and collections, depending on the data type and JDK version:
-
Arrays.sort() for primitive types (int, long, double, etc.) — uses the Dual-Pivot Quicksort algorithm. This is a fast sorting method with improvements, with an average complexity of O(n log n), but in the worst case, it can degrade to O(n²).
-
Arrays.sort() for objects (e.g., Integer, String) — since Java 7, it uses TimSort, a hybrid algorithm based on merging and insertion. It is stable and efficient for partially sorted data.
-
Collections.sort() — internally calls Arrays.sort() for lists, using TimSort.
Features:
- Dual-Pivot Quicksort is faster than classic Quicksort but unstable.
- TimSort is stable and works well on real data with already partially sorted elements.
Example usage:
int[] arr = {5, 3, 8, 1};
Arrays.sort(arr); // Dual-Pivot Quicksort for int
List<String> list = Arrays.asList("banana", "apple", "pear");
Collections.sort(list); // TimSort for objects